Linux 拨号vps windows公众号手机端

Python中xml转json的方法是什么

lewis 8年前 (2017-05-11) 阅读数 9 #程序编程
文章标签 python

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
版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门