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  输出的 t 如果有汉字的话都默认给转换成一堆编码 如果加上的话 就都能正常显示变成了汉字

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

[{"category": {"label": "u65b0u8f66"}, "title": "u5168u65b0u8d77u4e9au798fu745eu8feau8defu8bd5u8c0du7167u66ddu5149 u6216u4e3au5b9au540dK3", "url": "http://auto.sohu.com/20120523/n343878794.shtml", "source": "u641cu72d0u6c7du8f66", "time": 1337740004, "imgUrl": ""}, {"category": {"label": "u65b0u8f66"}, "title": "u65b0u5965u8feaQ7/Q8u66f4u591au4fe1u606fu66ddu5149 u5c06u57fau4e8eMLBu5e73u53f0", "url": "http://auto.sohu.com/20120523/n343873150.shtml", "source": "u641cu72d0u6c7du8f66", "time": 1337737913, "imgUrl": ""}]  

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

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



我们在post请求数据时,响应的内容是json数据,但是返回的json数据中文显示有问题,变成 uXXX的形式。这是因为中文以 unicode 编码了,而默认是以ASCII解析的,中文不在ASCII编码中,所以无法显示。

这时候我们可以用 import json 然后调用json.loads() 和json.dumps()来使中文正确显示。 下面的代码(data是中文不能正常显示的json串,newjson是处理后中文正常显示的字符串)

    1.  
      import json
    2.  
      myjson=json.loads(data) #data是向 api请求的响应数据,data必须是字符串类型的
    3.  
      newjson=json.dumps(myjson,ensure_ascii=False) #ensure_ascii=False 就不会用 ASCII 编码,中文就可以正常显示了
    4.  
       
    5.  
      print newjson
原文地址:https://www.cnblogs.com/lnd-blog/p/12535401.html