如何使用 json.dumps() - Python 正确打印扩展 ASCII 字符

How to print Extended ASCII characters correctly with json.dumps() - Python

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

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

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

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"
        }
    ]
}
>>>

您正在查找 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')