
学习前言活动地址:CSDN21天学习挑战赛
1.1 通过本次学习将获得通过昨日学习,了解python针对json和python对象的转换,今日延续昨日的激情,继续学习python中xml与json的互相转换。
需要先记住的一些概念
Python除了有自己内置函数,还有标准库以及第三方库。在Python中文网上面,我们可以清晰的看到两个菜单,标准库和第三方库。
首先安装第三方库,需要执行命令安装
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
✍️ 小技巧:
1.3 JSON文件转为XML文件
- 如果想查看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.xml1.4 XML文件转为JSON文件小明 男 18
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文件