文件未从 xml 正确转换为 JSON

File not converting to JSON properly from xml

我正在使用 Python 将数据从 xml 文件转换为 json 并将其放入文件中。我正在使用 xmltodict 使用 'parse' 转换为字典,然后使用 'dumps' 转换为 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)

Here is a sample xml file that I have used。但是,在输出中,我得到了一些不太像 json 的东西,添加了反斜杠。看起来像乱码:-

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

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

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

json_data = json.loads(json_data)