【问题标题】:How to print Extended ASCII characters correctly with json.dumps() - Python如何使用 json.dumps() 正确打印扩展 ASCII 字符 - Python
【发布时间】:2019-05-29 22:02:40
【问题描述】:

我有这个 JSON 文件,其中包含一些属于 Extended ASCII characters 的字符,例如 », •, ñ, Ó, Ä

{
    "@index": "1",
    "row": [
    {
        "col": [
        {
            "text": {
            "@x": "1",
            "#text": "Text » 1 A\\CÓ"
            }
        }
        ]
    },
    {
        "col": [
        {
            "text": {
            "@x": "7",
            "#text": "Text • 2 Wñ"
            }
        }
        ]
    }
    ]
}

我将它加载到d 变量中,json.load() 如下所示

import json 

with open('in.json') as f:
    d = json.load(f)

d 看起来像这样:

d = {'@index': '1', 'row': [{'col': [{'text': {'@x': '1', '#text': 'Text » 1 A\\CÓ'}}]}, {'col': [{'text': {'@x': '7', '#text': 'Text • 2 Wñ'}}]}]}

然后应用以下代码,将d中存储的json转换为一级嵌套json(到这里,扩展ASCII字符就可以了)

>>> z = {**d, 'row':[c['text'] for b in d['row'] for c in b['col']]}
>>> z
{'@index': '1', 'row': [{'@x': '1', '#text': 'Text » 1 A\\CÓ'}, {'@x': '7', '#text': 'Text • 2 Wñ'}]}
>>>

当我使用 json.dumps() 时出现问题,因为扩展的 ASCII 字符打印错误,如下所示。

如何解决这个问题?谢谢你的帮助。

>>> print(json.dumps(z, indent=4))
{
    "@index": "1",
    "row": [
        {
            "@x": "1",
            "#text": "Text \u00bb 1 A\\C\u00d3"
        },
        {
            "@x": "7",
            "#text": "Text \u2022 2 W\u00f1"
        }
    ]
}
>>>

【问题讨论】:

  • 字符没有打印“错误”; \uXXXX 转义是表示字符的一种完全有效的替代方式。
  • 但我需要它们是人类可读的。我希望有意义。

标签: python json extended-ascii


【解决方案1】:

您正在寻找ensure_ascii 参数。

import json                   

raw_data = '{"data": ["»", "•", "ñ", "Ó", "Ä"]}'
json_data = json.loads(raw_data)

print(json_data)
# {u'data': [u'\xbb', u'\u2022', u'\xf1', u'\xd3', u'\xc4']}

processed_data = json.dumps(json_data, indent=4, ensure_ascii=False, encoding='utf-8')

print(processed_data)
# {
#     "data": [
#         "»", 
#         "•", 
#         "ñ", 
#         "Ó", 
#         "Ä"
#     ]
# }

对于 Python2,你会这样做:

processed_data = json.dumps(json_data, indent=4, ensure_ascii=False).encode('utf-8')

【讨论】:

  • 非常感谢您的帮助。您的示例代码在 python2 中适用于我,而这一行 json.dumps(json_data, ...ensure_ascii=False).encode('utf-8') 在 Python3 中适用于我。但是当我在 Python3 中测试时,print(processed_data) 看起来像这样 b'{\n "data": [\n "\xc2\xbb",\n .. 不像您示例中的漂亮打印。
猜你喜欢
  • 2011-01-09
  • 2011-03-18
  • 2021-07-01
  • 1970-01-01
  • 2019-04-22
  • 2017-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多