人生苦短 记录关于 xml 和 json 相互转化的方法

Yellow · 2019年05月15日 · 909 次阅读

背景

在接口自动化中,当请求参数和响应参数的格式都是 xml 格式时,需要对参数进行处理,将 json 格式的请求参数转换为 xml 格式,将 xml 的响应参数转换为 json 格式。

第三方库

安装支持 xml 和 json 相互转换的第三方库:[xmltodict]

pip install xmltodict

json 转换为 xml

# 接收一个json文件路径参数
def json_to_xml(json_path):
    try:
        with open(json_path,'rb') as file_object:
            json_str = file_object.read()
        convertXml = ''
        jsDict = json.loads(json_str)
        #如果xml标签中间的数值存在特定的标记,需要在转换前拼接
        for key,value in jsDict.items():
          jsDict[key] = "[["+value+"]]" 
        convertXml = xmltodict.unparse(jsDict,pretty=True,encoding='utf-8')
        return convertXml
    except FileNotFoundError:
        print("File Not Found")    

xml 转换为 json

def xml_to_json(xml_path):
    try:
        xml_file = open(xml_path,'rb')
        xml_str = xml_file.read()
        converteJson = xmltodict.parse(xml_str,encoding='utf-8')
        jsonStr = json.dumps(converteJson,indent=4)
        return jsonStr
    except FileNotFoundError:
       print("File Not Found")

补充:当需要处理的 json 串是多维字典时,需要额外进行处理

def handle_json(self,json_dict):
    for key,value in json_dict.items():
        if not isinstance(json_dict[key],dict):
            json_dict[key] = "<![CDATA[" + str(value) + "]]>"
        else:
            handle_json(json_dict[key])
    return json_dict
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册