python2下解决json的unicode编码问题

基础知识:

  序列化——json.dumps()函数是将一个Python数据类型列表进行json格式的编码(可以这么理解,json.dumps()函数是将字典转化为json字符串)

  反序列化——json.loads()函数是将json格式数据转换为字典(可以这么理解,json.loads()函数是将json字符串转化为字典)

python 2下使用json.loads往往会导致最终的结果编码是unicode,并不是我们想要的str型,如下所示:

  test = {"name": "扎克伯格", "age":18}
  print test
  test_json = json.dumps(test, ensure_ascii=False)   ——中文打印会默认为ASCII,所以显示Unicode,需要将ensure_ascii=False才会显示中文
  print test_json
  test1 = json.loads(test_json)
  print test1

运行的结果是:

{'age': 18, 'name': '\xe6\x89\x8e\xe5\x85\x8b\xe4\xbc\xaf\xe6\xa0\xbc'}
{"age": 18, "name": "扎克伯格"}
{u'age': 18, u'name': u'\u624e\u514b\u4f2f\u683c'}

猜你喜欢

转载自www.cnblogs.com/blogofzxf/p/11096250.html
今日推荐