需求:json轉成xmlpython
實現:json的字段數量、層級未知,利用遞歸完成遍歷,拼接成xml格式json
測試json數據格式:測試
test.py:優化
#!/usr/bin/python
# -*- coding: UTF-8 -*-code
def rec(key, json):
if type(json) is dict:
print("<%s>" % key)
for key, value in json.items():
rec(key, value)
print("</%s>" % key)
else:
print("<%s>%s</%s>" % (key, json, key))xml
json = {"data":{"bills":{"id":"34534534","num":"20180509","error":{"total":"xxxxxxxxxxx不一致","message":"xxxxx不一致"},"error_img_map":{"total_amount":["圖片1","圖片2"],"img":["圖片1","圖片2"]},"result":"成功/不成功"}},"code":200,"message":"ok"}blog
rec("?xml version=\"1.0\" encoding=\"utf-8\"?", json)遞歸
測試結果:圖片
<?xml version="1.0" encoding="utf-8"?>
<data>
<bills>
<id>34534534</id>
<num>20180509</num>
<error>
<total>xxxxxxxxxxx不一致</total>
<message>xxxxx不一致</message>
</message>
<error_img_map>
<total_amount>['圖片1', '圖片2']</total_amount>
<img>['圖片1', '圖片2']</img>
</img>
<result>成功/不成功</result>
</result>
</bills>
<code>200</code>
<message>ok</message>
</message>utf-8
不喜輕噴,若有優化思路,煩請教教我~~