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

Soviut对lxml objectify的建议是好的。通过一个特殊的子类simplejson,您可以将lxml objectify结果转换为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("1.50W. Shakespeare")

>>> 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)

请参见docstring的用法示例,本质上是将lxmlobjectify的结果传递给objectJSONEncoder实例的encode方法

注意,Koen的观点在这里非常有效,上面的解决方案只适用于简单的嵌套xml,不包括根元素的名称。这是可以解决的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值