通过昨日学习,了解python针对json和python对象的转换,今日延续昨日的激情,继续学习python中xml与json的互相转换。
需要先记住的一些概念
Python除了有自己内置函数,还有标准库以及第三方库。在Python中文网上面,我们可以清晰的看到两个菜单,标准库和第三方库。
import
关键字引入后,才可以使用。例如:import json
。import
关键字引入后,才可以使用。还有一些非Python语言写成的库,例如引入java、C等语言的第三方库。第三方库主要用于以下几种用途: 首先安装第三方库,需要执行命令安装
pip install xmltodict
# 安装
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
首先,在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>
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))