将具有多个条目的 JSON 文件转换为 XML

时间:2021-07-05 07:20:06

标签: python arrays json xml

我的输入 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"}]

2 个答案:

答案 0 :(得分:1)

json2xml 是强大的 Python 库之一。试试这个。

json.json

[{"id":1,"author":"abc","title":"xyz"}, {"id":2,"author":"def","title":"mno"}]

Python

from json2xml import json2xml
import lxml.etree as ET
import json

with open('json.json') as data_file:
    data = json.load(data_file)


json2xml = json2xml.Json2xml(data, wrapper="sequence", pretty=True, attr_type=False).to_xml()
with open('json2xml.xml', 'w') as f:
    f.write(json2xml)
    
    
## modifie xml data
tree = ET.parse('json2xml.xml')
root = tree.getroot()
for item in root.findall('item'):
    for child in item:
        root.append(child)
    root.remove(item)


new_xml = ET.tostring(root, pretty_print=True, xml_declaration=True, encoding="UTF-8")
with open('file.xml', 'wb' ) as final:
    final.write(new_xml)

答案 1 :(得分:0)

能否修改json数据,做成数组?

{
    "updated": "2020-07-09",
    "list": [
         {"id":1,"author":"abc","title":"xyz"},
         {"id":2,"author":"def","title":"mno"}
    ]
}

import json as j
with open('data.json') as data_file:    
data = json.load(data_file)
for obj in data['list']:

r = e.Element("sequence")

e.SubElement(r,"id").text = obj["list"]["id"]
e.SubElement(r,"submitter").text = obj["list"]["submitter"]
e.SubElement(r,"authors").text = str(obj["list"]["authors"])
e.SubElement(r,"title").text = str(obj["list"]["title"])   

a = e.ElementTree(r)

a.write("json_to_xml.xml")
相关问题