python的 json.dumps 中文编码

python的 json.dumps 中文编码

  • # -- coding: utf-8 -- 的作用:文件内容以utf-8编码
  • json.dumps 序列化时对中文默认使用的ascii编码, print json.dumps(m)输出unicode编码的结果
  • 字符串在Python内部的表示是unicode编码。

  • 因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。

  • decode的作用是将其他编码的字符串转换成unicode编码

    decode('utf-8')表示将utf-8编码的字符串转换成unicode编码。

  • encode的作用是将unicode编码转换成其他编码的字符串

    encode('gb2312'),表示将unicode编码的字符串转换成gb2312编码。

  • python3中没有这种问题,所以最简单的方法是引入__future__模块,把新版本的特性导入到当前版本

  from __future__ import unicode_literals

  print json.dumps(m,ensure_ascii=False)

参考:https://blog.csdn.net/u014431852/article/details/53058951

原文地址:https://www.cnblogs.com/shengulong/p/9521604.html