栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Python

技术学习:Python(04) |欲先善其事,必先利其器(JSON)二

Python 更新时间:发布时间: 百科书网 趣学号

活动地址: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

小明18
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文件

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/1033006.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号