xmltodict unparse()函数Python 3出现值错误

2024-06-16 09:37:36 发布

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

我在使用xmltoict将json转换为xml时遇到了困难。它可以很好地处理单个根和单个对象,但是当我试图转换多个对象时,它返回一个ValueError“ValueError:documentwithmultipleroot”。在

以下是我的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))

结果:

^{pr2}$

任何帮助都将不胜感激,谢谢!在


Tags: ofjsonnewinformationpngfixturepointcapacity
2条回答

您可以使用xmljson库来使用不同的XML JSON conventions进行转换。它通过返回一个元素数组来支持多个根。在

例如:

>>> import xmljson
>>> xmljson.badgerfish.etree({'x': 1, 'y': 2})
[<Element y at 0x3114a08>, <Element x at 0x3114a48>]

返回xy元素。在

假设您已经清理了输入以使其有效(参见对问题的评论)。。。在

看起来xmltodict试图为列表中的每个项生成一个markers元素,而且由于markers位于顶层,所以您试图创建多个根。在

我会在数据周围添加一个顶层元素,如下所示:

y2 = {'root':y2}

相关问题 更多 >