我想从一个给定的url获取json数据,而json数据必须转换成xml格式

2024-09-28 05:17:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从给定的url获取JSON数据

http://www.deanclatworthy.com/imdb/?=The+Green+Mile

并将JSON数据转换为XML。我使用了^{}和{a2}将JSON对象转换成python字典。在

这是我的代码:

^{pr2}$

结果是:

{"imdbid":"tt0120689","imdburl":"http:\/\/www.imdb.com\/title\/tt0120689\/","genres":"Crime,Drama,Fantasy,Mystery","languages":"English ,French","country":"USA","votes":"281023","stv":0,"series":0,"rating":"8.4","title":"The Green Mile","year":"1999","usascreens":2875,"ukscreens":340}

{'ukscreens': 340, 'rating': '8.4', 'genres': 'Crime,Drama,Fantasy,Mystery', 'title': 'The Green Mile', 'series': 0, 'imdbid': 'tt0120689', 'year': '1999', 'votes': '281023', 'languages': 'English ,French', 'stv': 0, 'country': 'USA', 'usascreens': 2875, 'imdburl': 'http://www.imdb.com/title/tt0120689/'}

Tags: the数据comjsonhttptitlewwwgreen
3条回答

既然有了一个可用的python字典,就必须将其写入xml。在

您的xml格式是什么样的?Python在标准库中提供了一些用于编写/处理xml的工具。http://docs.python.org/library/xml.dom.minidom.html

因为python不知道xml文档的结构,所以编写需要一些工作。一点谷歌的调查可以起到很大的作用。在

ActiveState的recipes页面(由Cory Fabre编写)上有一个非常重要的条目,用于将python dict与XML进行转换。我最近用了一点,看起来效果不错。以下是链接:

http://code.activestate.com/recipes/573463-converting-xml-to-dictionary-and-back/

如果您足够幸运,JSON结构可以很好地映射到XML结构,那么这可能会很有用。在

使用requestsdict2xml库:

>>> import requests
>>> r = requests.get("http://www.deanclatworthy.com/imdb/?q=The+Green+Mile")
>>> import dict2xml
>>> xml = dict2xml.dict2xml(r.json)
>>> print xml
<country>USA</country>
<genres>Crime,Drama,Fantasy,Mystery</genres>
<imdbid>tt0120689</imdbid>
<imdburl>http://www.imdb.com/title/tt0120689/</imdburl>
<languages>English,French</languages>
<rating>8.5</rating>
<runtime>189min</runtime>
<series>0</series>
<stv>0</stv>
<title>The Green Mile</title>
<ukscreens>340</ukscreens>
<usascreens>2875</usascreens>
<votes>344054</votes>
<year>1999</year>

相关问题 更多 >

    热门问题