参考文章:
'''
Descripttion: XML与JSON格式相互转换
'''
# !pip install xmltodict
import json
import xmltodict
b = '''<?xml version="1.0" encoding="UTF-8"?>
<ProbeMatch>
<Uuid>BC06ADDD-2934-4B51-8246-3604E13B0A83</Uuid>
<Types>inquiry</Types>
<DeviceType>147256</DeviceType>
<DeviceDescription>DS-2CD3T86FWDA4-LS</DeviceDescription>
<DeviceSN>DS-2CD3T86FWDA4-LS20220517AACHJ90521185</DeviceSN>
<CommandPort>8000</CommandPort>
<HttpPort>80</HttpPort>
<MAC>80-7c-62-b3-53-85</MAC>
<IPv4Address>192.168.0.64</IPv4Address>
<IPv4SubnetMask>255.255.255.0</IPv4SubnetMask>
<IPv4Gateway>192.168.0.1</IPv4Gateway>
<IPv6Address>::</IPv6Address>
<IPv6Gateway>::</IPv6Gateway>
<IPv6MaskLen>64</IPv6MaskLen>
<DHCP>false</DHCP>
<AnalogChannelNum>0</AnalogChannelNum>
<DigitalChannelNum>1</DigitalChannelNum>
<SoftwareVersion>V5.7.1build 220309</SoftwareVersion>
<DSPVersion>V7.3 build 211201</DSPVersion>
<BootTime>2022-07-09 09:07:09</BootTime>
<Encrypt>true</Encrypt>
<ResetAbility>false</ResetAbility>
<DiskNumber>1</DiskNumber>
<Activated>true</Activated>
<PasswordResetAbility>true</PasswordResetAbility>
<PasswordResetModeSecond>true</PasswordResetModeSecond>
<SupportSecurityQuestion>true</SupportSecurityQuestion>
<SupportHCPlatform>true</SupportHCPlatform>
<HCPlatformEnable>true</HCPlatformEnable>
<IsModifyVerificationCode>true</IsModifyVerificationCode>
<Salt>f23c32b6630844732d6af341e3c32e0a8d11ec9e1d721a845fdc55397818374c</Salt>
<DeviceLock>flase</DeviceLock>
<SDKOverTLSPort>8443</SDKOverTLSPort>
<SDKServerStatus>true</SDKServerStatus>
<SDKOverTLSServerStatus>true</SDKOverTLSServerStatus>
<SupportMailBox>true</SupportMailBox>
<supportEzvizUnbind>true</supportEzvizUnbind>
<codeEncrypt>true</codeEncrypt>
</ProbeMatch>
'''
# 定义xml转json的函数
def xml_to_json(xml_str):
# parse是的xml解析器
xml_parse = xmltodict.parse(xml_str)
# json库dumps()是将dict转化成json格式,loads()是将json转化成dict格式。
# dumps()方法的ident=1,格式化json
json_str = json.dumps(xml_parse, indent=1)
return json_str
a = {
"user_info": {
"id": 12,
"name": "Tom",
"age": 12,
"height": 160,
"score": 100,
"variance": 12
}
}
# json转xml函数
def json_to_xml(json_str):
# xmltodict库的unparse()json转xml
# 参数pretty 是格式化xml
xml_str = xmltodict.unparse(json_str, pretty=1)
return xml_str
print("---------------------------分割线----------------------------------")
print(xml_to_json(b))
print("---------------------------分割线----------------------------------")
print(json_to_xml(a))
print("---------------------------分割线----------------------------------")