我有这个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"
}
]
}
>>>发布于 2019-05-30 06:12:32
您正在寻找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')https://stackoverflow.com/questions/56369117
复制相似问题