dict 转换成json_Python XML转换为JSON,XML转换为Dict

dict 转换成json

Today we will learn how to convert XML to JSON and XML to Dict in python. We can use python xmltodict module to read XML file and convert it to Dict or JSON data. We can also stream over large XML files and convert them to Dictionary. Before stepping into the coding part, let’s first understand why XML conversion is necessary.

今天,我们将学习如何在python中将XML转换为JSON,将XML转换为Dict。 我们可以使用python xmltodict模块读取XML文件并将其转换为Dict或JSON数据。 我们还可以流式传输大型XML文件并将其转换为Dictionary。 在进入编码部分之前,让我们首先了解为什么需要XML转换。

将XML转换为Dict / JSON (Converting XML to Dict/JSON)

XML files have slowly become obsolete but there are pretty large systems on the web that still uses this format. XML is heavier than JSON and so, most developers prefer the latter in their applications.

XML文件已逐渐过时,但是Web上有相当大的系统仍在使用这种格式。 XML比JSON重,因此,大多数开发人员在其应用程序中更喜欢后者。

When applications need to understand the XML provided by any source, it can be a tedious task to convert it to JSON. The xmltodict module in Python makes this task extremely easy and straightforward to perform.

当应用程序需要了解任何来源提供的XML时,将其转换为JSON可能是一项繁琐的任务。 Python中的xmltodict模块使此任务非常容易执行。

xmltodict入门 (Getting started with xmltodict)

We can get started with xmltodict module but we need to install it first. We will mainly use pip to perform the installation.

我们可以开始使用xmltodict模块,但是我们需要先安装它。 我们将主要使用pip进行安装。

安装xmltodict模块 (Install xmltodict module)

Here is how we can install the xmltodict module using Python Package Index (pip):

这是我们如何使用Python Package Index(pip)安装xmltodict模块的方法:

pip install xmltodict

This will be done quickly as xmltodict is a very light weight module. Here is the output for this installation:

这将很快完成,因为xmltodict是一个非常轻量的模块。 这是此安装的输出:

The best thing about this installation was that this module is not dependent on any other external module and so, it is light-weight and avoids any version conflicts.

关于此安装的最好的事情是该模块不依赖于任何其他外部模块,因此它是轻量级的,并且避免了任何版本冲突。

Just to demonstrate, on Debian based systems, this module can be easily installed using the apt tool:

为了演示,在基于Debian的系统上,可以使用apt工具轻松安装此模块:

sudo apt install python-xmltodict

Another plus point is that this module has an official Debian package.

另外一点是,该模块具有官方的Debian软件包

Python XML到JSON (Python XML to JSON)

The best place to start trying this module will be to perform an operation it was made to perform primarily, to perform XML to JSON conversions. Let’s look at a code snippet on how this can be done:

开始尝试此模块的最佳位置是执行最初执行的操作,以执行XML到JSON的转换。 让我们看一下如何做到这一点的代码片段:

import xmltodict
import pprint
import json

my_xml = """
    <audience>
      <id what="attribute">123</id>
      <name>Shubham</name>
    </audience>
"""

pp = pprint.PrettyPrinter(indent=4)
pp.pprint(json.dumps(xmltodict.parse(my_xml)))

Let’s see the output for this program:

python xml to json

让我们看一下该程序的输出:

Here, we simply use the parse(...) function to convert XML data to JSON and then we use the json module to print JSON in a better format.

在这里,我们仅使用parse(...)函数将XML数据转换为JSON,然后使用json模块以更好的格式打印JSON。

将XML文件转换为JSON (Converting XML File to JSON)

Keeping XML data in the code itself is neither always possible nor it is realistic. Usually, we keep our data in either database or some files. We can directly pick files and convert them to JSON as well. Let’s look at a code snippet how we can perform the conversion with an XML file:

将XML数据保留在代码本身中既不总是可行的,也不是现实的。 通常,我们将数据保存在数据库或某些文件中。 我们可以直接选择文件并将它们也转换为JSON。 让我们看一下代码片段,该如何使用XML文件执行转换:

import xmltodict
import pprint
import json

with open('person.xml') as fd:
    doc = xmltodict.parse(fd.read())

pp = pprint.PrettyPrinter(indent=4)
pp.pprint(json.dumps(doc))

Let’s see the output for this program:

python xml file to json

让我们看一下该程序的输出:

Here, we used another module pprint to print the output in a formatted manner. Apart from that, using the open(...) function was straightforward, we used it get a File descriptor and then parsed the file into a JSON object.

在这里,我们使用了另一个模块pprint以格式化的方式打印输出。 除此之外,使用open(...)函数非常简单,我们使用它获取了File描述符,然后将文件解析为JSON对象。

Python XML进行分类 (Python XML to Dict)

As the module name suggest itself, xmltodict actually converts the XML data we provide to just a simply Python dictionary. So, we can simply access the data with the dictionary keys as well. Here is a sample program:

正如模块名称所暗示的那样,xmltodict实际上将我们提供的XML数据转换为一个简单的Python字典 。 因此,我们也可以简单地使用字典键访问数据。 这是一个示例程序:

import xmltodict
import pprint
import json

my_xml = """
    <audience>
      <id what="attribute">123</id>
      <name>Shubham</name>
    </audience>
"""
my_dict = xmltodict.parse(my_xml)
print(my_dict['audience']['id'])
print(my_dict['audience']['id']['@what'])

Let’s see the output for this program:

python xml to dict

让我们看一下该程序的输出:

So, the tags can be used as the keys along with the attribute keys as well. The attribute keys just need to be prefixed with the @ symbol.

因此,标签也可以与属性键一起用作键。 属性键只需要以@符号为前缀。

在XML中支持命名空间 (Supporting Namespaces in XML)

In XML data, we usually have a set of namespaces which defines the scope of the data provided by the XML file. While converting to the JSON format, it is then necessary that these namespaces persist in the JSON format as well. Let us consider this sample XML file:

在XML数据中,我们通常有一组命名空间,用于定义XML文件提供的数据范围。 在转换为JSON格式时,这些名称空间也必须保持JSON格式。 让我们考虑以下示例XML文件:

<root xmlns="https://defaultns.com/"
        xmlns:a="https://a.com/">
    <audience>
        <id what="attribute">123</id>
        <name>Shubham</name>
    </audience>
</root>

Here is a sample program on how we can include XML namespaces in the JSON format as well:

这是一个示例程序,说明如何包含JSON格式的XML名称空间:

import xmltodict
import pprint
import json

with open('person.xml') as fd:
    doc = xmltodict.parse(fd.read(), process_namespaces=True)

pp = pprint.PrettyPrinter(indent=4)
pp.pprint(json.dumps(doc))

Let’s see the output for this program:

xml namespace to dict and json

让我们看一下该程序的输出:

JSON到XML的转换 (JSON to XML conversion)

ALthough converting from XML to JSON is the prime objective of this module, xmltodict also supports doing the reverse operation, converting JSON to XML form. We will provide the JSON data in program itself. Here is a sample program:

尽管从XML转换为JSON是此模块的主要目标,但xmltodict还支持进行反向操作,将JSON转换为XML形式。 我们将在程序本身中提供JSON数据。 这是一个示例程序:

import xmltodict

student = {
  "data" : {
    "name" : "Shubham",
    "marks" : {
      "math" : 92,
      "english" : 99
    },
    "id" : "s387hs3"
  }
}

print(xmltodict.unparse(student, pretty=True))

Let’s see the output for this program:

python json to xml

让我们看一下该程序的输出:

Please note that giving a single JSON key is necessary for this to work correctly. If we consider that we modify our program to contain multiple JSON keys at the very first level of data like:

请注意,只有一个JSON密钥才能正常工作。 如果我们认为我们将程序修改为在数据的第一层包含多个JSON键,例如:

import xmltodict

student = {
    "name" : "Shubham",
    "marks" : {
        "math" : 92,
        "english" : 99
    },
    "id" : "s387hs3"
}

print(xmltodict.unparse(student, pretty=True))

In this case, we have three keys at the root level. If we try to unparse this form of JSON, we will face this error:

python json to xml unparse error

在这种情况下,我们在根级别具有三个键。 如果我们尝试解析这种形式的JSON,则会遇到此错误:

This happens because xmltodict needs to construct the JSON with the very first key as the root XML tag. This means that there should only be a single JSON key at the root level of data.

发生这种情况是因为xmltodict需要使用第一个键作为根XML标记构造JSON。 这意味着在数据的根级别只能有一个JSON密钥。

结论 (Conclusion)

In this lesson, we studied an excellent Python module which can be used to parse and convert XML to JSON and vice-versa. We also learned how to convert XML to Dict using xmltodict module.

在本课程中,我们研究了一个出色的Python模块,该模块可用于解析XML并将其转换为JSON,反之亦然。 我们还学习了如何使用xmltodict模块将XML转换为Dict。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/19392/python-xml-to-json-dict

dict 转换成json

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值