我有这个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"
}
]
}
>>>
答案 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')