带有重音符号的Python转储json [英] Python dump json with accents

查看:126
本文介绍了带有重音符号的Python转储json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何打印带有特殊字符如à"或ç"的json?

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

我可以这样打印:

import json

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

output:

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

如果我使用'ensure_ascii = False'

if i use 'ensure_ascii=False'

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

如何使用json克服特殊字符问题?当我使用pystache并尝试打印pystache.render('Hi {{person}}!',weird_dict)时,我需要进行渲染:

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)"

推荐答案

指定ensure_ascii=False参数:

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

根据 json模块文档:

如果sure_ascii为True(默认值),则 输出以\ uXXXX序列转义,结果为str 实例仅包含ASCII字符.如果sure_ascii为 错误,某些写入fp的块可能是unicode实例.这 通常是因为输入包含unicode字符串或 使用编码参数.除非fp.write()明确理解 unicode(如codecs.getwriter()中的代码)可能会导致错误.

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.

这篇关于带有重音符号的Python转储json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆