可能重复:
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)
发布于 2010-03-27 08:16:58
苏维埃关于lxml对象化的建议是好的。使用一个特殊的子类simplejson,您可以将lxml对象化结果转换为json。
import simplejson as json
import lxml
class objectJSONEncoder(json.JSONEncoder):
"""A specialized JSON encoder that can handle simple lxml objectify types
>>> from lxml import objectify
>>> obj = objectify.fromstring("<Book><price>1.50</price><author>W. Shakespeare</author></Book>")
>>> objectJSONEncoder().encode(obj)
'{"price": 1.5, "author": "W. Shakespeare"}'
"""
def default(self,o):
if isinstance(o, lxml.objectify.IntElement):
return int(o)
if isinstance(o, lxml.objectify.NumberElement) or isinstance(o, lxml.objectify.FloatElement):
return float(o)
if isinstance(o, lxml.objectify.ObjectifiedDataElement):
return str(o)
if hasattr(o, '__dict__'):
#For objects with a __dict__, return the encoding of the __dict__
return o.__dict__
return json.JSONEncoder.default(self, o)
有关用法的示例,请参阅文档字符串,实际上是将lxml的结果传递给objectJSONEncoder
实例的objectify
方法
注意,Koen的观点在这里非常有效,上面的解决方案只适用于简单的嵌套xml,不包括根元素的名称。这是可以修复的。
我在这里的要点中包含了这个类:http://gist.github.com/345559
发布于 2012-04-18 09:03:23
xmltodict (完全公开:这是我写的)可以帮助您按照这个"standard"将XML转换为dict+list+string结构。它是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"]}}'
发布于 2009-01-23 12:51:49
我认为XML格式可以如此多样化,以至于如果没有一个非常严格定义的XML格式,就不可能编写能够做到这一点的代码。我的意思是:
<persons>
<person>
<name>Koen Bok</name>
<age>26</age>
</person>
<person>
<name>Plutor Heidepeen</name>
<age>33</age>
</person>
</persons>
会变成
{'persons': [
{'name': 'Koen Bok', 'age': 26},
{'name': 'Plutor Heidepeen', 'age': 33}]
}
但这会是什么呢:
<persons>
<person name="Koen Bok">
<locations name="defaults">
<location long=123 lat=384 />
</locations>
</person>
</persons>
懂得我的意思吗?
编辑:刚找到这篇文章:http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html
https://stackoverflow.com/questions/471946
复制相似问题