![f695ef5d61c4e6fda17a296088341f78.png](https://i-blog.csdnimg.cn/blog_migrate/07360c89abc4c472f4d50a9a53ac94ef.png)
问题描述
今天写了一个python脚本,所有编码默认utf-8,通过json.dumps转为json,结果使用print打印出来,打印结果的中文字符一直显示为xxxxxxxxxx
原因
找个半天终于发现了问题所在:
$ help('json')
从中发现以下说明:
| __init__(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None)
…………
| If *ensure_ascii* is true (the default), all non-ASCII
| characters in the output are escaped with uXXXX sequences,
| and the results are str instances consisting of ASCII
| characters only. If ensure_ascii is False, a result may be a
| unicode instance. This usually happens if the input contains
| unicode strings or the *encoding* parameter is used.
说明json.dumps默认把所有中文字符转为了ascii,而我们使用的是utf-8,所以print出来中文不对
解决方法
为调用的json.dumps方法加入ensure_ascii=False参数就OK了,如下所示
$ json.dumps({"data": data}, ensure_ascii=False, indent=2)
{
"data": [
{
"{#REALURL}": "测试_xxx"
},
{
"{#REALURL}": "测试_xxx"
},
.
.
.
]
}