What is the method for converting XML to JSON in Python?

There are several ways to convert XML to JSON in Python, with one common method being to use the third-party library xmltodict. Below is an example code:

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)

By running the above code, the following JSON string will be outputted.

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

Please note that this example uses the xmltodict library, so it needs to be installed first. You can install it using the following command:

pip install xmltodict
Leave a Reply 0

Your email address will not be published. Required fields are marked *