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

时间:2019-05-29 22:02:41

标签: python json extended-ascii

我有这个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"
        }
    ]
}
>>>

1 个答案:

答案 0 :(得分: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')