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

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

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

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


当前回答

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

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

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

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

其他回答

你可能想看看http://designtheory.org/library/extrep/designdb-1.0.pdf。这个项目从一个大型XML文件库的XML到JSON转换开始。在转换过程中进行了大量研究,并生成了最简单直观的XML -> JSON映射(在本文前面有描述)。总之,将所有内容转换为JSON对象,并将重复块作为对象列表。

表示键/值对的对象(Python中的字典,Java中的hashmap, JavaScript中的对象)

没有映射回XML以获得相同的文档,原因是,键/值对是属性还是<key>value</key>,因此该信息丢失。

如果你问我,我会说属性是一个入门;但它们在HTML上也很好用。

您可以使用xmljson库使用不同的XML JSON约定进行转换。

例如,这个XML:

<p id="1">text</p>

通过BadgerFish惯例翻译为:

{
  'p': {
    '@id': 1,
    '$': 'text'
  }
}

并通过GData约定转换成这个(不支持属性):

{
  'p': {
    '$t': 'text'
  }
}

... 并通过Parker约定转换为这个(不支持属性):

{
  'p': 'text'
}

可以使用相同的方法从XML转换为JSON,也可以从JSON转换为XML 约定:

>>> import json, xmljson
>>> from lxml.etree import fromstring, tostring
>>> xml = fromstring('<p id="1">text</p>')
>>> json.dumps(xmljson.badgerfish.data(xml))
'{"p": {"@id": 1, "$": "text"}}'
>>> xmljson.parker.etree({'ul': {'li': [1, 2]}})
# Creates [<ul><li>1</li><li>2</li></ul>]

披露:这个库是我写的。希望它能帮助未来的搜索者。

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

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

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

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

如果您不想使用任何外部库和第三方工具,请尝试下面的代码。

Code

import re
import json

def getdict(content):
    res=re.findall("<(?P<var>\S*)(?P<attr>[^/>]*)(?:(?:>(?P<val>.*?)</(?P=var)>)|(?:/>))",content)
    if len(res)>=1:
        attreg="(?P<avr>\S+?)(?:(?:=(?P<quote>['\"])(?P<avl>.*?)(?P=quote))|(?:=(?P<avl1>.*?)(?:\s|$))|(?P<avl2>[\s]+)|$)"
        if len(res)>1:
            return [{i[0]:[{"@attributes":[{j[0]:(j[2] or j[3] or j[4])} for j in re.findall(attreg,i[1].strip())]},{"$values":getdict(i[2])}]} for i in res]
        else:
            return {res[0]:[{"@attributes":[{j[0]:(j[2] or j[3] or j[4])} for j in re.findall(attreg,res[1].strip())]},{"$values":getdict(res[2])}]}
    else:
        return content

with open("test.xml","r") as f:
    print(json.dumps(getdict(f.read().replace('\n',''))))

样例输入

<details class="4b" count=1 boy>
    <name type="firstname">John</name>
    <age>13</age>
    <hobby>Coin collection</hobby>
    <hobby>Stamp collection</hobby>
    <address>
        <country>USA</country>
        <state>CA</state>
    </address>
</details>
<details empty="True"/>
<details/>
<details class="4a" count=2 girl>
    <name type="firstname">Samantha</name>
    <age>13</age>
    <hobby>Fishing</hobby>
    <hobby>Chess</hobby>
    <address current="no">
        <country>Australia</country>
        <state>NSW</state>
    </address>
</details>

输出

[
  {
    "details": [
      {
        "@attributes": [
          {
            "class": "4b"
          },
          {
            "count": "1"
          },
          {
            "boy": ""
          }
        ]
      },
      {
        "$values": [
          {
            "name": [
              {
                "@attributes": [
                  {
                    "type": "firstname"
                  }
                ]
              },
              {
                "$values": "John"
              }
            ]
          },
          {
            "age": [
              {
                "@attributes": []
              },
              {
                "$values": "13"
              }
            ]
          },
          {
            "hobby": [
              {
                "@attributes": []
              },
              {
                "$values": "Coin collection"
              }
            ]
          },
          {
            "hobby": [
              {
                "@attributes": []
              },
              {
                "$values": "Stamp collection"
              }
            ]
          },
          {
            "address": [
              {
                "@attributes": []
              },
              {
                "$values": [
                  {
                    "country": [
                      {
                        "@attributes": []
                      },
                      {
                        "$values": "USA"
                      }
                    ]
                  },
                  {
                    "state": [
                      {
                        "@attributes": []
                      },
                      {
                        "$values": "CA"
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  },
  {
    "details": [
      {
        "@attributes": [
          {
            "empty": "True"
          }
        ]
      },
      {
        "$values": ""
      }
    ]
  },
  {
    "details": [
      {
        "@attributes": []
      },
      {
        "$values": ""
      }
    ]
  },
  {
    "details": [
      {
        "@attributes": [
          {
            "class": "4a"
          },
          {
            "count": "2"
          },
          {
            "girl": ""
          }
        ]
      },
      {
        "$values": [
          {
            "name": [
              {
                "@attributes": [
                  {
                    "type": "firstname"
                  }
                ]
              },
              {
                "$values": "Samantha"
              }
            ]
          },
          {
            "age": [
              {
                "@attributes": []
              },
              {
                "$values": "13"
              }
            ]
          },
          {
            "hobby": [
              {
                "@attributes": []
              },
              {
                "$values": "Fishing"
              }
            ]
          },
          {
            "hobby": [
              {
                "@attributes": []
              },
              {
                "$values": "Chess"
              }
            ]
          },
          {
            "address": [
              {
                "@attributes": [
                  {
                    "current": "no"
                  }
                ]
              },
              {
                "$values": [
                  {
                    "country": [
                      {
                        "@attributes": []
                      },
                      {
                        "$values": "Australia"
                      }
                    ]
                  },
                  {
                    "state": [
                      {
                        "@attributes": []
                      },
                      {
                        "$values": "NSW"
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
]

XML和JSON之间不存在“一对一”的映射,因此将一个转换为另一个必须了解您想对结果做什么。

也就是说,Python的标准库有几个用于解析XML的模块(包括DOM、SAX和ElementTree)。从Python 2.6开始,JSON模块中包含了对Python数据结构与JSON之间转换的支持。

所以基础设施就在那里。