Python下XML与JSON字符串互相转换

#-*-coding:utf-8-*-
import xmltodict
import json
import os
import sys

def jsonToXML(json_str):
    '''传入字典字符串或字典,返回xml字符串'''
    xml_str = ''
    if type(json_str) == dict:
        dic = json_str
    else:
        dic = json.loads(json_str)
    try:
        xml_str = xmltodict.unparse(dic, encoding='utf-8')  # 示例字典字符串下这段代码会报错
    except Exception as e:
        xml_str = xmltodict.unparse({'request': dic}, encoding='utf-8')  # request可根据需求修改,目的是为XML字符串提供顶层标签
    finally:
        return xml_str

def xmlToJson(xml_str):
    '''传入xml字符串,返回字典'''
    dic = xmltodict.parse(xml_str, encoding='utf-8')
    dic = json.dumps(dic, indent=4)
    return dic

if __name__ == '__main__':
    s = ' text text '
    dic = {"bbox":"-180,70,-178,72", "enable_has_geo":"on", "has_geo":"1", "geo_context":"", "lat": 41.4, "lon": 116.1, "enable_extras":"on","per_page":"250", "enable_page":"on", "page":"1", "format":"json", "sign_call":"full"}
    result = xmlToJson(s)
    result = jsonToXML(dic)
    print(result)

参考博客:
[1] python中将xml格式转json格式

你可能感兴趣的:(python)