【问题标题】:Python dump json with accents [duplicate]带有重音符号的Python转储json [重复]
【发布时间】:2014-11-11 16:40:07
【问题描述】:

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

我可以这样打印:

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'

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

如何使用 json 解决特殊字符问题?当我使用 pystache 并尝试打印时,我需要进行渲染

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

【问题讨论】:

  • 哪个版本的 Python?那些是 Unicode 字符串吗?
  • weird_json 不是 JSON,而是 Python 字典。
  • @Joe:输出 JSON。
  • @MartijnPieters 对不起。我声称午后失明。
  • @Joe:当然;我认为 OP 只是试图说明输出。

标签: python json pystache


【解决方案1】:

指定ensure_ascii=False 参数:

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

根据json module documentation

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

【讨论】:

    猜你喜欢
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    • 2014-06-01
    • 2013-07-05
    相关资源
    最近更新 更多