使用 Python 将 XML 转换为 JSON? [英] Converting XML to JSON using Python?

查看:42
本文介绍了使用 Python 将 XML 转换为 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网络上看到了相当多的难看的 XML->JSON 代码,并且与 Stack 的用户进行了一段时间的互动,我相信这群人比 Google 结果的前几页可以提供更多帮助.

I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can.

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

So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're looking now into Python-based solutions.

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

This public weather.com RSS feed is a good example of what we'd be parsing (our actual weather.com feed contains additional information because of a partnership w/them).

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

In a nutshell, how should we convert XML to JSON using Python?

推荐答案

XML 和 JSON 之间没有一对一"映射,因此将一个转换为另一个必须需要了解您想要什么结果.

There is no "one-to-one" mapping between XML and JSON, so converting one to the other necessarily requires some understanding of what you want to do with the results.

话虽如此,Python 的标准库有几个用于解析 XML 的模块(包括 DOM、SAX 和 ElementTree).从 Python 2.6 开始,json 模块.

That being said, Python's standard library has several modules for parsing XML (including DOM, SAX, and ElementTree). As of Python 2.6, support for converting Python data structures to and from JSON is included in the json module.

所以基础设施就在那里.

So the infrastructure is there.

这篇关于使用 Python 将 XML 转换为 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆