python实现json转XML
最近要在客戶服務(wù)器上做一個接口,需要從另一個系統(tǒng)拉取數(shù)據(jù)到本地,對方提供了resftful接口服務(wù),返回是json數(shù)據(jù),需要轉(zhuǎn)換為xml。但是基于客戶服務(wù)器是linux系統(tǒng),并且無法連外網(wǎng),linux默認(rèn)安裝了2.7.x版本的python,便手動實(shí)現(xiàn)了一個python函數(shù),不用在服務(wù)器上安裝第三方依賴
#!/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
?
打印出結(jié)果:<root><message>ok</message><code>200</code><data><num>20180509</num><id>34534534</id></data><data><num>20180509</num><id>34534534</id></data></root>
總結(jié)
以上是生活随笔為你收集整理的python实现json转XML的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot自定义starter
- 下一篇: websocket python爬虫_p