python递归实现json转xml 简单好用

需求:json转成xmlpython

实现:json的字段数量、层级未知,利用递归完成遍历,拼接成xml格式json

测试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

不喜轻喷,若有优化思路,烦请教教我~~

相关文章
相关标签/搜索