Python中JSON在解析的同时进行自定义编码处理

python 转换为json时候 汉字编码问题

  有这样一个需求:

  需要一个json 文件 数据从数据库里查询出来

  1. 设置文件头

  # -*- coding:utf-8 -*-

  2. 连接数据库 将数据库连接数据库的编码设置为utf8  

  db = MySQLdb.connect(host='数据库,user=用户名,passwd=密码,db='数据库, init_command="set names utf8" )

  3. 查询出来的数据转化为json

  t = json.dumps(r, ensure_ascii=False)

  注意: ensure_ascii=False

  python 的api是这样解释的:

  If ensure_ascii is False (default: True), then some chunks written to fp may be unicode instances, subject to normal Python str to unicode coercion rules. Unless fp.write() explicitly understands unicode (as in codecs.getwriter()) this is likely to cause an error.

  PS : e文不好 就不再这里误导了。

  如果 不加 ensure_ascii=False 输出的 t 如果有汉字的话都默认给转换成一堆编码 如果加上的话 就都能正常显示变成了汉字

  例如:

  不加的话: t = json.dumps(r)

  [{"category": {"label": "\u65b0\u8f66"}, "title": "\u5168\u65b0\u8d77\u4e9a\u798f\u745e\u8fea\u8def\u8bd5\u8c0d\u7167\u66dd\u5149 \u6216\u4e3a\u5b9a\u540dK3", "url": "", "source": "\u641c\u72d0\u6c7d\u8f66", "time": 1337740004, "imgUrl": ""}, {"category": {"label": "\u65b0\u8f66"}, "title": "\u65b0\u5965\u8feaQ7/Q8\u66f4\u591a\u4fe1\u606f\u66dd\u5149 \u5c06\u57fa\u4e8eMLB\u5e73\u53f0", "url": "", "source": "\u641c\u72d0\u6c7d\u8f66", "time": 1337737913, "imgUrl": ""}]

  加上的话: t = json.dumps(r, ensure_ascii=False)

  [{"category": {"label": "新车"}, "title": "全新起亚福瑞迪路试谍照曝光 或为定名K3", "url": "", "source": "汽车", "time": 1337740004, "imgUrl": ""}, {"category": {"label": "新车"}, "title": "新奥迪Q7/Q8更多信息曝光 将基于MLB平台", "url": "", "source": "汽车", "time": 1337737913, "imgUrl": ""}]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值