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 jsonmy_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:

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

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 jsonwith 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:

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

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 jsonmy_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:

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

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 jsonwith 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:

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

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 xmltodictstudent = {"data" : {"name" : "Shubham","marks" : {"math" : 92,"english" : 99},"id" : "s387hs3"}
}print(xmltodict.unparse(student, pretty=True))

Let’s see the output for this program:

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

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 xmltodictstudent = {"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:

在这种情况下,我们在根级别具有三个键。 如果我们尝试解析这种形式的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

dict 转换成json_Python XML转换为JSON,XML转换为Dict相关推荐

  1. Java XML转换为JSON XML解析 转换为JSON Java 实现JSON转换为XML json转xml

    Java XML转换为JSON XML解析 转换为JSON Java 实现JSON转换为XML json转xml 一.转换代码 1.XML字符串转换为JSON /*** description: XM ...

  2. python把dict转成json_Python dict(或对象)与json之间的互相转化

    Python dict(或对象)与json之间的互相转化 原文转载自 1.JSON:JavaScript 对象表示法,是轻量级的文本数据交换格式,独立于语言,平台 2.JSON 语法规则 数据在名称/ ...

  3. 将表格转换成纯html,HTML table表格转换为Markdown table表格

    举个栗子,当我想要把这个页面的第一个表格转换成Markdown Table时,怎么做更快,效率更高? 只需简单三步,请看示例: 第一步:复制包含HTML table标签的代码 复制table代码(HT ...

  4. php将json转换成对象,php将json转换成对象或数组

    php将json转换成对象或数组 发布时间:2020-06-01 16:31:29 来源:亿速云 阅读:126 作者:鸽子 在PHP中可以使用json_decode()函数将JSON编码的字符串转换为 ...

  5. cr3格式怎么转换成jpg_怎么把JPG格式转换为PDF?

    以前我写过怎么把PDF格式的文件转换为Word文档,也写过怎么怎么把Word转换为JPG图片格式. 今天再写一篇:怎么把图片格式转换为PDF格式文件. 也是用上次的五张图片作为例子做测试 现在我们只需 ...

  6. linux mbr转换成gpt分区格式,MBR怎么转换为GPT?硬盘MBR格式转换成GPT格式教程

    硬盘MBR格式怎么转换成GPT格式?这是很多小白电脑用户所不了解的.首先介绍一下硬盘gpt格式,GPT是一种全局唯一标识分区表(GUID Partition Table,缩写:GPT),是指全局唯一标 ...

  7. 测试软件能批量转换成pdf吗,cad如何批量转换为pdf软件

    CAD转换成PDF的方法有很多,那么大家知道cad如何批量转换为pdf软件吗?下面是学习啦小编整理的方法,希望能给大家解答. cad批量转换为pdf软件的方法: 1.首先要打开所有要转换的dwg文件, ...

  8. 图片怎么转换成pdf格式?其实图片转换为pdf很简单

    图片怎么转换成pdf格式?pdf作为我们日常生活中十分常见的一种格式之一,和我们的生活息息相关,我们在日常生活中无时无刻不在接触pdf格式.除了word文档转换为pdf文件之外,其实图片也是可以存放在 ...

  9. java小数转换成分数_如何将小数转换为分数?

    我需要将小数转换为分数.转换成10英尺很容易. 1.5 => 15/10 这可以通过以下代码完成: public class Rational { private int num, denom; ...

最新文章

  1. 程序员的周末:纯野的一天
  2. serverless 框架_研发的未来在哪里?Serverless 云开发来了!
  3. tensorflow和keras的版本问题
  4. 中继技术助威 Wi-Fi网路涵盖范围三级跳
  5. 20145307《信息安全系统设计基础》课程总结
  6. js下拉 selenium_如何使用Python / Selenium webdriver处理Angularjs / Javascript下拉列表?
  7. 关于excel中的查找
  8. redis cluster集群模式简述
  9. python与office结合可以干什么-Python 进行Office开发(以Word为例)
  10. Python全栈之路系列----之-----守护进程\进程锁\队列\生产者消费者模式\数据共享\进程池(同步,异步)\回调函数\concurrent.futures模块...
  11. 深入理解java:1.1. 类加载器
  12. Silverlight 里获取摄像头视频
  13. 我的本科毕业论文——Messar即时通讯系统
  14. matlab dpabi安装,Android 8 应用安装时 ABI 确认过程
  15. 学成在线案例(开发具体步骤)
  16. 怎么把网页保存成pdf格式-最简单操作
  17. ArcGIS读取天地图2.0
  18. 《设计模式之禅》-原型模式
  19. java silk转mp3,小程序录音后格式转换问题请教
  20. 什么是三次握手和四次握手

热门文章

  1. [转载] python set 集合详解
  2. [转载] python下 import Matplotlib.pyplot as plt 的使用
  3. [转载] Java中为什么要有重载现象
  4. MATLAB IIR滤波器设计函数buttord与butter
  5. 《计算机网络 自顶向下方法》 第2章 应用层 Part1
  6. one list to muti list
  7. MyBatis-Spring-Boot 使用总结
  8. 深入理解JVM之JVM内存区域与内存分配
  9. utuntu 视频 无声
  10. 数据库设计还是不是信息系统的核心?