【发布时间】:2021-07-05 07:20:06
【问题描述】:
我的输入 json 文件看起来像这样
{"id":1,"author":"abc","title":"xyz"}
{"id":2,"author":"def","title":"mno"}
我想要一个 python 脚本来创建一个看起来像这样的 xml 文件
<sequence>
<id>1</id>
<author>abc</author>
<title>xyz</title>
</sequence>
<sequence>
<id>2</id>
<author>def</author>
<title>mno</title>
</sequence>
现在这是我正在使用的代码
import json as j
with open("test.json") as json_format_file:
d = j.load(json_format_file)
import xml.etree.cElementTree as e
r = e.Element("sequence")
e.SubElement(r,"id").text = d["id"]
e.SubElement(r,"submitter").text = d["submitter"]
e.SubElement(r,"authors").text = str(d["authors"])
e.SubElement(r,"title").text = str(d["title"])
a = e.ElementTree(r)
a.write("json_to_xml.xml")
问题是它只适用于 1 个条目,如果我在 JSON 文件中有超过 1 个条目,它会引发错误。我怎样才能让这个运行多个条目并将其全部写入 xml 文件?
编辑: 已将我的 JSON 文件更改为如下所示
[{"id":1,"author":"abc","title":"xyz"},
{"id":2,"author":"def","title":"mno"}]
【问题讨论】:
-
您的输入文件是无效的 JSON。一个有效的 json 文件看起来像
[{"id":1,"author":"abc","title":"xyz"}, {"id":2,"author":"def","title":"mno"}] -
啊,好吧,如果我将我的 JSON 文件更改为这样,它会起作用吗?
-
至少你可以使用
for inner_dict in d: ...并使用inner_dict["id"]等。 -
嗯,好的,我去看看。太棒了!