python实现json转XML
最近要在客戶服務器上做一個接口,需要從另一個系統拉取數據到本地,對方提供了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>
總結
以上是生活随笔為你收集整理的python实现json转XML的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot自定义starter
- 下一篇: python语音朗读