写一个json2xml的代码
时间: 2023-03-14 20:05:27 浏览: 70
以下是一个json2xml的代码示例:
import json
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
def json2xml(json_obj, line_padding=""):
result_list = list()
json_obj_type = type(json_obj)
if json_obj_type is list:
for sub_elem in json_obj:
result_list.append(json2xml(sub_elem, line_padding))
return "\n".join(result_list)
if json_obj_type is dict:
for tag_name in json_obj:
sub_obj = json_obj[tag_name]
if isinstance(sub_obj, dict):
result_list.append("%s<%s>" % (line_padding, tag_name))
result_list.append(json2xml(sub_obj, "\t" + line_padding))
result_list.append("%s</%s>" % (line_padding, tag_name))
elif isinstance(sub_obj, list):
result_list.append("%s<%s>" % (line_padding, tag_name))
result_list.append(json2xml(sub_obj, line_padding + "\t"))
result_list.append("%s</%s>" % (line_padding, tag_name))
else:
result_list.append("%s<%s>%s</%s>" % (line_padding, tag_name, sub_obj, tag_name))
return "\n".join(result_list)
阅读全文