我在使用xmltodict将json转换为xml时遇到问题。它可以与单个根和单个对象一起正常工作,但是当我尝试转换多个对象时,它将返回ValueError“ ValueError:具有多个根的文档”。
这是我的JSON数据:
到目前为止,这是我的脚本:
import json
import xmltodict
y = """{{ "markers":[ { "point":"new GLatLng(40.266044,-74.718479)","awayTeam":"LUGip","markerImage":"images/red.png","fixture":"Wednesday 7pm","information":"Linux users group meets second Wednesday of each month.","previousScore":"","capacity":"","homeTeam":"Lawrence Library"},{ "point":"new GLatLng(40.211600,-74.695702)","awayTeam":"LUGip HW SIG","tv":"","markerImage":"images/white.png","fixture":"Tuesday 7pm","information":"Linux users can meet the first Tuesday of the month to work out harward and configuration issues.","capacity":"","homeTeam":"Hamilton Library"},{ "point":"new GLatLng(40.294535,-74.682012)","awayTeam":"After LUPip Mtg Spot","tv":"","markerImage":"images/newcastle.png","fixture":"Wednesday whenever","information":"Some of us go there after the main LUGip meeting, drink brews, and talk.","capacity":"2 to 4 pints","homeTeam":"Applebees"}]}"""
y2 = json.loads(y)
print(xmltodict.unparse(y2, pretty = True))
结果:
Traceback (most recent call last):
File "<ipython-input-89-8838ce8b0d7f>", line 1, in <module>
print(xmltodict.unparse(y2,pretty=True))
File "/Users/luzazul/anaconda/lib/python3.4/site-packages/xmltodict.py", line 323, in unparse
raise ValueError('Document must have exactly one root.')
ValueError: Document must have exactly one root.
任何帮助将不胜感激,谢谢!
最佳答案
假设您已经清理了输入以使其有效(请参阅问题注释)...
看起来xmltodict试图为列表中的每个项目创建一个markers
元素,并且由于markers
在顶层,因此您试图创建多个根。
我将通过在数据周围添加一个顶级元素来解决这个问题:
y2 = {'root':y2}