Convert xml format data to json

How to convert xml code into json format code?
Here, I used to introduce the xmltodict dependency package and use xmltodict to solve this problem.
First, install xmltodict:

pip install xmltodict==0.12.0

Secondly, the sample xml is parsed into json to demonstrate:

# -*- coding: utf-8 -*-
import xmltodict
import json
a = '''
<LogonRequest xmlns="http://www.ibm.com/xmlns/systems/power/firmware/web/mc/2012_10/" schemaVersion="V1_1_0">
 <Metadata>
 <Atom/>
 </Metadata>
 <UserID kb="CUR" kxe="false">1111</UserID>
 <Password kb="CUR" kxe="false">2222</Password>
</LogonRequest>
'''
if __name__ == '__main__':
    
    json_dict = xmltodict.parse(a, encoding='utf-8')
   	# json_dict   是xml转成字典
    json_str = json.dumps(json_dict, indent=2)
    print json_str  #  返回json字符串(并不是json)
    json_data = json.loads(json_str)  # 可以进一步转成json

The results are as follows:
Insert picture description here

注意:xml转成json使用xmltodict依赖包,很容易解析中含有@、#等·特殊符号,
我的解决办法是可以在转成json字符串之后,采用字符替换,将@、#等特殊符号替换掉,
这样就可以转成正常的json。

Guess you like

Origin blog.csdn.net/qq_42631707/article/details/102502120