Python dump json with accents [duplicate]

放肆的年华 提交于 2020-05-12 11:45:08

问题


How can i print a json with special characters as "à" or "ç"?

I can print like this:

import json

weird_dict ={"person": "ç", "á": 'à', "ç": 'ã'}
print json.dumps(weird_dict, indent=4, sort_keys=True)

output:

{
    "person": "\u00e7", 
    "\u00e1": "\u00e0", 
    "\u00e7": "\u00e3"
}

if i use 'ensure_ascii=False'

weird_dict={"person": "ç", "á": 'à', "ç": 'ã'}
print json.dumps(weird_dict, indent=4, sort_keys=True, ensure_ascii=False)
output:
{
    "person": "ç", 
    "á": "à", 
    "ç": "ã"
}

How to overcome special characters issue using json? I need to render when i use pystache and try to print pystache.render('Hi {{person}}!', weird_dict) it occurs me:

"'ascii' codec can't decode byte 0xc3 in position 4770: ordinal not in range(128)"

回答1:


Specify ensure_ascii=False argument:

>>> import json
>>>
>>> d = {"person": "ç", "á": 'à', "ç": 'ã'}
>>> print json.dumps(d, indent=4, sort_keys=True, ensure_ascii=False)
{
    "person": "ç",
    "á": "à",
    "ç": "ã"
}

According to json module documentation:

If ensure_ascii is True (the default), all non-ASCII characters in the output are escaped with \uXXXX sequences, and the result is a str instance consisting of ASCII characters only. If ensure_ascii is False, some chunks written to fp may be unicode instances. This usually happens because the input contains unicode strings or the encoding parameter is used. Unless fp.write() explicitly understands unicode (as in codecs.getwriter()) this is likely to cause an error.



来源:https://stackoverflow.com/questions/25894039/python-dump-json-with-accents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!