irpas技术客

python实现json转XML_yuchii_json转xml python

irpas 2978

最近要在客户服务器上做一个接口,需要从另一个系统拉取数据到本地,对方提供了resftful接口服务,返回是json数据,需要转换为xml。但是基于客户服务器是linux系统,并且无法连外网,linux默认安装了2.7.x版本的python,便手动实现了一个python函数,不用在服务器上安装第三方依赖

#!/usr/bin/python # -*- coding: UTF-8 -*- content="" def json_to_xml(key, json): ? ? ? ? global content ? ? ? ? if type(json) is dict: ? ? ? ? ? if key != "": ? ? ? ? ? ? ? ? content=content+"<%s>" % key ? ? ? ? ? for key1, value in json.items(): ? ? ? ? ? ? ? ? json_to_xml(key1, value) ? ? ? ? ? if key !="": ? ? ? ? ? ? ? ? content=content+"</%s>" % key ? ? ? ? elif ?type(json) is list: ? ? ? ? ? ? for l in json: ? ? ? ? ? ? ? ? content=content+"<%s>" % key ? ? ? ? ? ? ? ? json_to_xml("",l) ? ? ? ? ? ? ? ? content=content+"</%s>" % key ? ? ? ? else: ? ? ? ? ? ? content=content+"<%s>%s</%s>" % (key, json, key) json = {"data":[{"id":"34534534","num":"20180509"},{"id":"34534534","num":"20180509"}],"code":200,"message":"ok"} json_to_xml("root",json) print content ?

打印出结果:<root><message>ok</message><code>200</code><data><num>20180509</num><id>34534534</id></data><data><num>20180509</num><id>34534534</id></data></root>


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #Json转xml #Python