我在网上看到过相当多笨拙的XML->JSON代码,并与Stack的用户进行了一些互动,我相信这群人能比谷歌结果的前几页提供更多的帮助。

因此,我们正在解析一个天气提要,我们需要在许多网站上填充天气小部件。我们现在正在研究基于python的解决方案。

这个公共weather.com RSS提要是我们将要解析的内容的一个很好的例子(我们实际的weather.com提要包含额外的信息,因为与他们有合作关系)。

简而言之,如何使用Python将XML转换为JSON ?


当前回答

我不久前在github上发表了一篇文章。

https://github.com/davlee1972/xml_to_json

这个转换器是用Python编写的,将一个或多个XML文件转换为JSON / JSONL文件

它需要一个XSD模式文件来找出嵌套的json结构(字典vs列表)和json等效数据类型。

python xml_to_json.py -x PurchaseOrder.xsd PurchaseOrder.xml

INFO - 2018-03-20 11:10:24 - Parsing XML Files..
INFO - 2018-03-20 11:10:24 - Processing 1 files
INFO - 2018-03-20 11:10:24 - Parsing files in the following order:
INFO - 2018-03-20 11:10:24 - ['PurchaseOrder.xml']
DEBUG - 2018-03-20 11:10:24 - Generating schema from PurchaseOrder.xsd
DEBUG - 2018-03-20 11:10:24 - Parsing PurchaseOrder.xml
DEBUG - 2018-03-20 11:10:24 - Writing to file PurchaseOrder.json
DEBUG - 2018-03-20 11:10:24 - Completed PurchaseOrder.xml

我也有一个后续的xml到拼花转换器,以类似的方式工作

https://github.com/blackrock/xml_to_parquet

其他回答

可能最简单的方法是将XML解析为字典,然后用simplejson序列化它。

检查lxml2json(披露:我写的)

https://github.com/rparelius/lxml2json

它非常快速、轻量级(只需要lxml),一个优点是您可以控制某些元素是转换为列表还是字典

虽然用于XML解析的内置库非常好,但我更倾向于lxml。

但是对于解析RSS提要,我推荐Universal Feed Parser,它也可以解析Atom。 它的主要优点是它甚至可以消化大多数畸形的饲料。

Python 2.6已经包含了一个JSON解析器,但是速度有所提高的新版本是simplejson。

有了这些工具,构建你的应用应该不会那么困难。

我不久前在github上发表了一篇文章。

https://github.com/davlee1972/xml_to_json

这个转换器是用Python编写的,将一个或多个XML文件转换为JSON / JSONL文件

它需要一个XSD模式文件来找出嵌套的json结构(字典vs列表)和json等效数据类型。

python xml_to_json.py -x PurchaseOrder.xsd PurchaseOrder.xml

INFO - 2018-03-20 11:10:24 - Parsing XML Files..
INFO - 2018-03-20 11:10:24 - Processing 1 files
INFO - 2018-03-20 11:10:24 - Parsing files in the following order:
INFO - 2018-03-20 11:10:24 - ['PurchaseOrder.xml']
DEBUG - 2018-03-20 11:10:24 - Generating schema from PurchaseOrder.xsd
DEBUG - 2018-03-20 11:10:24 - Parsing PurchaseOrder.xml
DEBUG - 2018-03-20 11:10:24 - Writing to file PurchaseOrder.json
DEBUG - 2018-03-20 11:10:24 - Completed PurchaseOrder.xml

我也有一个后续的xml到拼花转换器,以类似的方式工作

https://github.com/blackrock/xml_to_parquet

献给任何可能还需要这个的人。下面是一个更新的、简单的代码来进行这种转换。

from xml.etree import ElementTree as ET

xml    = ET.parse('FILE_NAME.xml')
parsed = parseXmlToJson(xml)


def parseXmlToJson(xml):
  response = {}

  for child in list(xml):
    if len(list(child)) > 0:
      response[child.tag] = parseXmlToJson(child)
    else:
      response[child.tag] = child.text or ''

    # one-liner equivalent
    # response[child.tag] = parseXmlToJson(child) if len(list(child)) > 0 else child.text or ''

  return response