python json.dumps 中文

我们知道python 中json.dumps()函数用于将一个Python数据类型列表进行json格式的编码,换句话说json.dumps()函数是将字典转化为字符串。

比如:

import json
dic = {"name":"James"}
print(json.dumps(dic))

但是如果dict中包含中文,输出的str就是包含乱码的字符串。

如:

import json


dic = {"name":"哈哈"}
print(json.dumps(dic))


'''
输出:
{"name": "\u54c8\u54c8"}
'''

如果想要其输出中文,则需要添加参数ensure_ascii=False



dic = {"name":"哈哈"}
print(json.dumps(dic))

print(json.dumps(dic, ensure_ascii=False))


'''
{"name": "\u54c8\u54c8"}
{"name": "哈哈"}
'''
ensure_ascii参数的含义:
If ``ensure_ascii`` is false, then the return value can contain non-ASCII
characters if they appear in strings contained in ``obj``. Otherwise, all
such characters are escaped in JSON strings.

你可能感兴趣的:(MongoDB,python)