首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Python中将XML转换为JSON?

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

Stack Overflow用户
提问于 2009-01-23 05:12:30
回答 7查看 110.5K关注 0票数 65

可能重复:

Converting XML to JSON using Python?

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

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

代码语言:javascript
复制
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)
EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2010-03-27 08:16:58

苏维埃关于lxml对象化的建议是好的。使用一个特殊的子类simplejson,您可以将lxml对象化结果转换为json。

代码语言:javascript
复制
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

票数 27
EN

Stack Overflow用户

发布于 2012-04-18 09:03:23

xmltodict (完全公开:这是我写的)可以帮助您按照这个"standard"将XML转换为dict+list+string结构。它是Expat-based,所以它非常快,不需要在内存中加载整个XML树。

一旦拥有了该数据结构,就可以将其序列化为JSON:

代码语言:javascript
复制
import xmltodict, json

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

Stack Overflow用户

发布于 2009-01-23 12:51:49

我认为XML格式可以如此多样化,以至于如果没有一个非常严格定义的XML格式,就不可能编写能够做到这一点的代码。我的意思是:

代码语言:javascript
复制
<persons>
    <person>
        <name>Koen Bok</name>
        <age>26</age>
    </person>
    <person>
        <name>Plutor Heidepeen</name>
        <age>33</age>
    </person>
</persons>

会变成

代码语言:javascript
复制
{'persons': [
    {'name': 'Koen Bok', 'age': 26},
    {'name': 'Plutor Heidepeen', 'age': 33}]
}

但这会是什么呢:

代码语言:javascript
复制
<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

票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/471946

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档