栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

Soviut对于lxml objectify的建议是好的。使用特殊子类化的simplejson,您可以将lxml对象化结果转换为json。

import simplejson as jsonimport lxmlclass objectJSonEnprer(json.JSONEnprer):  """A specialized JSON enprer that can handle simple lxml objectify types      >>> from lxml import objectify      >>> obj = objectify.fromstring("<Book><price>1.50</price><author>W. Shakespeare</author></Book>")  >>> objectJSonEnprer().enpre(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.JSONEnprer.default(self, o)

请参阅文档字符串以获取用法示例,从本质上讲,您将lxml的结果传递

objectify
给的实例的enpre方法
objectJSONEnprer

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

我在以下要点中包含了该类:http :
//gist.github.com/345559



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/418341.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号