活动地址:CSDN21天学习挑战赛
🏮 学习前言
通过昨日学习,了解python针对json和python对象的转换,今日延续昨日的激情,继续学习python中xml与json的互相转换。
🎈1.1 通过本次学习将获得
- JSON文件转为XML文件
- XML文件转为JSON文件
- 解析JSON字符串
- 解析JSON文件
需要先记住的一些概念
Python除了有自己内置函数,还有标准库以及第三方库。在Python中文网上面,我们可以清晰的看到两个菜单,标准库和第三方库。
- 内置函数:无需导入,即可使用。例如:静态数字,内置函数加减乘除、绝对值、平均数等。
- 标准库:自带库,需要使用
import
关键字引入后,才可以使用。例如:import json
。 - 第三方库:需要安装后(有些第三方库可能还需要配置),使用
import
关键字引入后,才可以使用。还有一些非Python语言写成的库,例如引入java、C等语言的第三方库。第三方库主要用于以下几种用途:- 文件读写
- 网络抓取和解析
- 数据库连接
- 数据清洗转换
- 数据计算和统计分析
- 自然语言处理和文本挖掘
- 数据挖掘
- 机器学习
- 深度学习
- 图像处理
- 视频处理
- 音频处理
- 数据可视化
- 交互学习和集成开发
- 其他
🎈1.2 安装第三方库
首先安装第三方库,需要执行命令安装
- Windows
pip install xmltodict
- MacOS
# 安装
xxx $ pip install xmltodict
DEPRECATION: Configuring installation scheme with distutils config files is deprecated and will no longer work in the near future. If you are using a Homebrew or Linuxbrew Python, please see discussion at https://github.com/Homebrew/homebrew-core/issues/76621
Collecting xmltodict
Downloading xmltodict-0.13.0-py2.py3-none-any.whl (10.0 kB)
Installing collected packages: xmltodict
DEPRECATION: Configuring installation scheme with distutils config files is deprecated and will no longer work in the near future. If you are using a Homebrew or Linuxbrew Python, please see discussion at https://github.com/Homebrew/homebrew-core/issues/76621
DEPRECATION: Configuring installation scheme with distutils config files is deprecated and will no longer work in the near future. If you are using a Homebrew or Linuxbrew Python, please see discussion at https://github.com/Homebrew/homebrew-core/issues/76621
Successfully installed xmltodict-0.13.0
# 查询已安装第三方库列表
xxx $ pip list
Package Version
---------- -------
meson 0.58.1
pip 22.2.2
protobuf 3.17.3
setuptools 59.0.1
wheel 0.37.0
xmltodict 0.13.0
✍️ 小技巧:
- 如果想查看
pip
下面安装了什么工具库,可以执行命令pip list
- 如果想要升级
pip
,需要执行PYTHON_HOME/bin/python3.9 -m pip install --upgrade pip
🎈1.3 JSON文件转为XML文件
首先,在python的环境下面,我手工创建一个json文件,如下图所展示:
>>> import json
>>>
>>> person = {"person":{"name":"小明","sex":"男","age":18}}
>>>
>>> json.dump(person, open('person.json', 'w'), ensure_ascii = False)
使用cat
命令查看下写入的文件的内容,如下图所展示:
xxx$ cat person.json
{"person": {"name": "小明", "sex": "男", "age": 18}}
重点来了,我们现在需要将这个json文件转换为xml文件,那么需要在python环境下,执行如下命令,代码参考老师博文:
import xmltodict
import json
def json_to_xml(python_dict):
"""xmltodict库的unparse()json转xml
:param python_dict: python的字典对象
:return: xml字符串
"""
xml_str = xmltodict.unparse(python_dict)
return xml_str
JSON_PATH = './person.json' # json文件的路径
with open(JSON_PATH, 'r') as f:
jsonfile = f.read()
python_dict = json.loads(jsonfile) # 将json字符串转换为python字典对象
with open(JSON_PATH[:-4] + 'xml', 'w') as newfile:
newfile.write(json_to_xml(python_dict))
执行命令之后,查看目录下多了一个person.xml文件,打开文件我们看到了我们预期的效果,若下图展示:
xxx $ cat person.xml
<?xml version="1.0" encoding="utf-8"?>
<person><name>小明</name><sex>男</sex><age>18</age></person>
🎈1.4 XML文件转为JSON文件
import json
import xmltodict
def xml_to_json(xml_str):
"""parse是的xml解析器,参数需要
:param xml_str: xml字符串
:return: json字符串
"""
xml_parse = xmltodict.parse(xml_str)
# json库dumps()是将dict转化成json格式,loads()是将json转化成dict格式。
# dumps()方法的ident=1,格式化json
json_str = json.dumps(xml_parse, indent=1)
return json_str
XML_PATH = './person.xml' # xml文件的路径
with open(XML_PATH, 'r') as f:
xmlfile = f.read()
with open(XML_PATH[:-3] + 'json', 'w') as newfile:
newfile.write(xml_to_json(xmlfile))
🎈1.5 解析JSON字符串
🎈1.6 解析JSON文件