gpt4 book ai didi

python - 如何在 Python 中将 XML 转换为 JSON?

转载 作者:IT老高 更新时间:2023-10-28 12:44:21 24 4
gpt4 key购买 nike

Possible Duplicate:
Converting XML to JSON using Python?

我在 App Engine 上做一些工作,我需要将从远程服务器检索到的 XML 文档转换为等效的 JSON 对象。

我正在使用 xml.dom.minidom 来解析由 urlfetch 返回的 XML 数据。我还尝试使用 django.utils.simplejson 将解析的 XML 文档转换为 JSON。我完全不知道如何将两者结合在一起。下面是我正在修改的代码:

from xml.dom import minidom
from django.utils import simplejson as json

#pseudo code that returns actual xml data as a string from remote server.
result = urlfetch.fetch(url,'','get');

dom = minidom.parseString(result.content)
json = simplejson.load(dom)

self.response.out.write(json)

最佳答案

xmltodict (完全公开:我写的)可以帮助您将 XML 转换为 dict+list+string 结构,遵循 "standard" .是Expat -based,因此速度非常快,不需要将整个 XML 树加载到内存中。

一旦你有了那个数据结构,你就可以将它序列化为 JSON:

import xmltodict, json

o = xmltodict.parse('<e> <a>text</a> <a>text</a> </e>')
json.dumps(o) # '{"e": {"a": ["text", "text"]}}'

关于python - 如何在 Python 中将 XML 转换为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/471946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com