首页 > 解决方案 > 文件未从 xml 正确转换为 JSON

问题描述

我正在使用 Python 将数据从 xml 文件转换为 json 并将其放入文件中。我正在使用 xmltodict 使用“解析”转换为字典,然后使用“转储”转换为 json。这是下面的代码: -

import xmltodict
import json
with open('note.xml') as xml_file:
    my_dict=xmltodict.parse(xml_file.read())
xml_file.close()
json_data=json.dumps(my_dict)
with open('note.json', 'w') as f:
    json.dump(json_data, f)

这是我使用的示例 xml 文件。但是,在输出中,我得到的东西不像 json 那样,添加了反斜杠。看起来像胡言乱语:-

"{\"note\": {\"to\": \"Tove\", \"from\": \"Jani\", \"heading\": \"Reminder\", \"body\": \"Don't forget me this weekend!\"}}"

我试图理解为什么我无法以正确的 json 格式获取数据。我的代码有什么问题吗?请注意,我不是一个非常熟练的程序员,只偶尔使用过 Python。

标签: pythonjsonxmlconvertersxmltodict

解决方案


您需要在json_data=json.dumps(my_dict)将字符串转换为 json 对象之后添加以下代码

json_data = json.loads(json_data)

推荐阅读