温馨提示×

Python中xml转json的方法是什么

小亿
88
2023-12-26 23:15:57
栏目: 编程语言

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

0