python中json.dumps使用及字符编码

我们知道,python中的字符串分普通字符串和unicode字符串,一般从数据库中读取的字符串会自动被转换为unicode字符串

下面回到重点,使用json.dumps时,一般的用法为:

>>> obj={"name":"测试"}

>>> json.dumps(obj)
'{"name": "\\u6d4b\\u8bd5"}'

>>> print json.dumps(obj)
{"name": "\u6d4b\u8bd5"}

>>> json.dumps(obj).encode("utf-8") 
'{"name": "\\u6d4b\\u8bd5"}'

可以看到这里输出的字符串为普通字符串,但是里面的内容却是unicode字符串的内容,即使对结果进行encode("utf-8") ,因为这个字符串本身就已经编码过了,所有进行encode不会有变化.


要想得到字符串的真实表示,需要用到参数ensure_ascii=False(默认为True)

>>> json.dumps(obj,ensure_ascii=False)  
'{"name": "\xe6\xb5\x8b\xe8\xaf\x95"}'

>>> print json.dumps(obj,ensure_ascii=False)
{"name": "测试"}


猜你喜欢

转载自blog.csdn.net/weixin_40013463/article/details/80389038