Convert JSON to XML in Python

前端 未结 5 754
野趣味
野趣味 2020-12-01 07:40

I see a number of questions on SO asking about ways to convert XML to JSON, but I\'m interested in going the other way. Is there a python library for converting JSON to XML?

5条回答
  •  失恋的感觉
    2020-12-01 08:09

    If you don't have such a package, you can try:

    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]
                result_list.append("%s<%s>" % (line_padding, tag_name))
                result_list.append(json2xml(sub_obj, "\t" + line_padding))
                result_list.append("%s" % (line_padding, tag_name))
    
            return "\n".join(result_list)
    
        return "%s%s" % (line_padding, json_obj)
    

    For example:

    s='{"main" : {"aaa" : "10", "bbb" : [1,2,3]}}'
    j = json.loads(s)
    print(json2xml(j))
    

    Result:

    10 1 2 3

提交回复
热议问题