python - 文件未从 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。
解决方案
您需要在json_data=json.dumps(my_dict)
将字符串转换为 json 对象之后添加以下代码
json_data = json.loads(json_data)
推荐阅读
- php - 是否可以使用 Migrating 和 Seed Once 进行 InMemory 测试
- python - 代码不能作为函数工作,但可以在主代码中工作。(Python,pygame)
- django - Ajax - LocalHost 上的 500 内部服务器错误
- angular - 在更改事件之前以角度形式将先前选择的值存储在选择框中
- react-native - 如何使用 react-native-testing-library 提交表单或在输入上按 enter 键
- image - 大的 png 文件不会在 Chrome/Chromium 中呈现
- javascript - 如何使用 nodeJS 获取当前系统音量
- android - 您是否需要 android sdk 才能在真正的 android 设备上使用 appium?
- google-cloud-platform - GCP OAuth 同意屏幕 - 显示自定义数据
- c++ - 代码在 C++ 中运行得非常好,但在 Leetcode 上的 python 中提供 TLE