Python中xml转json的方法是什么

1150
2024/1/1 23:15:57
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

Python中将XML转换为JSON的方法有多种,其中一种常见的方法是使用第三方库xmltodict。下面是一个示例代码:

import xmltodict
import json

def xml_to_json(xml_string):
    # 将XML字符串解析为字典形式
    data_dict = xmltodict.parse(xml_string)
    
    # 将字典转换为JSON字符串
    json_string = json.dumps(data_dict)
    
    return json_string

# 要转换的XML字符串
xml_string = """
<root>
    <person>
        <name>John Doe</name>
        <age>30</age>
    </person>
    <person>
        <name>Jane Smith</name>
        <age>25</age>
    </person>
</root>
"""

# 调用函数进行转换
json_string = xml_to_json(xml_string)
print(json_string)

运行以上代码,将输出以下JSON字符串:

{
    "root": {
        "person": [
            {
                "name": "John Doe",
                "age": "30"
            },
            {
                "name": "Jane Smith",
                "age": "25"
            }
        ]
    }
}

请注意,此示例使用了xmltodict库,因此需要先安装该库。可以使用以下命令安装:

pip install xmltodict

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: python字符串降序排序怎么实现