将XML转换为JSON输出以进行前端解析



使用python上的xmltodict(v0.12.0(,我有一个xml,它将被解析并转换为json格式。例如:

XML:

<test temp="temp" temp2="temp2">This is a test</test>

将被转换为以下json:

"test": {
"@temp": "temp",
"@temp2": "temp2",
"#text": "This is a test"
}

我有一个前端解析器,它读取JSON对象并将它们转换为XML。不幸的是,标签需要以不同的方式成形。

前端解析器所期望的:

{
test: {
"@": {
temp: "temp",
temp2: "temp2"
},
"#": "This is a test"
}
}

我觉得这种格式最好在Python上进行修改,但我在迭代一个大得多的字典时遇到了一些麻烦,我们不知道xml会有多深,并且收集所有以"开头的键@"并在整个标签对象中给出它自己的对象。我可以用什么方法来塑造这些数据?

对于任何好奇的人来说,这就是我最终解决问题的方式。正如@furas所说,我决定递归是我的最佳选择。我最终迭代了我转换为JSON的原始xml数据,并使用错误的属性格式,然后创建了一个副本,同时找到了任何属性标记:

def structure_xml(data):
curr_dict = {}
for key,value in data.items():
if isinstance(value, dict):       
curr_dict[key] = structure_xml(value)
elif isinstance(value, list):  
value_list = []
for val in value:
if isinstance(val,dict) or isinstance(val,list):
value_list.append(structure_xml(val))
curr_dict[key] = value_list
else: 
if '@' in key:
new_key = key.split("@",1)[1] 
new_obj = { new_key: value }
if "@" in curr_dict:
curr_dict["@"][new_key] = value 
else:
curr_dict["@"] = new_obj
elif '#text' in key:
curr_dict['#'] = data[key]
else:
curr_dict[key] = data[key]
return curr_dict

最新更新