Home >Backend Development >Python Tutorial >How to use Python's json standard library

How to use Python's json standard library

PHPz
PHPzforward
2023-06-03 12:25:591406browse

"How

1. Overview of JSON basics

1. What is JSON?

JSON (full name: JavaScript Object Notation object notation) is a lightweight text data exchange format. The data format of JSON is actually the dictionary format in python , which can contain arrays enclosed in square brackets, which are lists in python.

  • JSON is language independent

  • JSON is self-descriptive and easier to understand

  • JSON than XML is smaller, faster, and easier to parse

  • Crawlers often obtain interface data, which is in JSON format

2. JSON long What does it look like?

Grammar format : {key1:value1, key2:value2,} Key-value pair format (separated by colon), use commas to connect the pairs

Simple case: JSON object

{
    "name": "小明", 
    "age": 18}

Complex case: JSON array

{
    "student":
        [
            {"name": "小明", "age": 11},
            {"name": "小红","age": 10}
        ],
    "classroom": {"class1": "room1", "class2": "room2"}}

3. Notes

1. The key part of the key-value pair of json must be wrapped in double quotes ", single quotes will not work (so if keywords appear in the key, they will also be characterized), and objects in js are not mandatory Requirements (so keywords are not allowed in the key).

2. The value part of the key-value pair of json is not allowed to have function, undefined, NaN, but it can have null, the value of the object in js can appear in.

3. After the json data ends, meaningless commas are not allowed to appear, such as: {"name":"admin","age":18,}, Pay attention to the comma after 18 at the end of the data, which is not allowed.

4. Summary of json format

The correct json format is as follows:

# 格式1:JSON 对象{"name": "admin", "age": 18}# 格式2:JSON 数组{
    "student":
        [
            {"name": "小明", "age": 18},
            {"name": "小红", "age": 16},
            {"name": "小黑", "age": 20}
        ]}

The wrong json format is as follows:

"How

2. json module

1. Function

1. Use jsON string to generate python object (load)

2. Format the python object into ison string (dump)

2. Data Type conversion

Converts data from Python to json format. There will be changes in data type, as shown in the following table:

##dictobjectlist, tuple arraystrstringint, float, int- & float-derived Enums numberTruetrue##FalseNoneIn turn, convert the json format into python built-in types, as shown in the following table:
Python JSON
false
null

JSON##objectdictarrayliststringstr number(int)intnumber(real)floattrueTruefalseFalseNone3. Usage methodThe use of the json module is actually very simple. For most situations, we only need to use the following four methods:
Python
##null

MethodFunction##json.dumps(obj)Convert python data type to json format string. Convert python data type and save it to a file in son format. Convert json format string to python type. Read data from a json format file and convert it to python type.

4、 json.dumps()

将python数据类型转换为json格式的字符串。

语法格式json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

>>> import json

# Python字典
>>> person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}
>>> print(person)
{'name': '小明', 'age': 30, 'tel': ['888888', '1351111111'], 'isonly': True}
>>> type(person)
<class &#39;dict&#39;

# Python字典转换为json字符串
>>> jsonStr = json.dumps(person) 
>>> print(jsonStr )
{"name": "\u5c0f\u660e", "age": 30, "tel": ["888888", "1351111111"], "isonly": true}
>>> type(jsonStr)
<class &#39;str&#39;>

从上可以看出json格式和Python格式的区别在于:python格式打印输出是单引号,类型为dict。而json格式打印输出是双引号,类型为:strTrue的开头大小写区别。

使用参数能让JSON字串格式化输出:

>>> print(json.dumps(person, sort_keys=True, indent=4, separators=(&#39;,&#39;, &#39;: &#39;))){
    "age": 30,
    "isonly": true,
    "name": "\u5c0f\u660e",
    "tel": [
        "888888",
        "1351111111"
    ]}

参数解读

  • sort_keys:是否排序

  • indent:定义缩进距离

  • separators:是一个元组,定义分隔符的类型

  • skipkeys:是否允许JSON字串编码字典对象时,字典的key不是字符串类型(默认是不允许)

修改分割符类型

>>> print(json.dumps(person, sort_keys=True, indent=4, separators=(&#39;!&#39;, &#39;-&#39;))){
    "age"-30!    "isonly"-true!    "name"-"\u5c0f\u660e"!    "tel"-[
        "888888"!        "1351111111"
    ]

文件操作

import json

person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}jsonStr = json.dumps(person)with open(&#39;test.json&#39;, &#39;w&#39;, encoding=&#39;utf-8&#39;) as f:  # 打开文件
    f.write(jsonStr)  # 在文件里写入转成的json串

查看生成的新文件:
"How

5、json.dump()

将python数据类型转换并保存到son格式的文件内。

语法格式json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

import json

person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}json.dump(person, open(&#39;data.json&#39;, &#39;w&#39;))

查看生成的新文件:
"How
使用参数能让JSON字串格式化输出:

import json

person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}json.dump(person, open(&#39;data.json&#39;, &#39;w&#39;), sort_keys=True, indent=4, separators=(&#39;,&#39;, &#39;: &#39;))

再次查看文件:
"How
json.dumpsjson.dump写入文件的区别

  • dump() 不需要使用.write()方法,只需要写那个字典,那个文件即可;而 dumps() 需要使用.write()方法写入。

  • 如果把字典写到文件里面的时候,dump()好用;但是如果不需要操作文件,或需要把内容存储到数据库何excel,则需要使用dumps()先把字典转换成字符串,再写入

6、json.loads()

将json格式的字符串转换为python的类型。

语法格式json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

>>> import json# Python字典>>> person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}>>> print(person){&#39;name&#39;: &#39;小明&#39;, &#39;age&#39;: 30, &#39;tel&#39;: [&#39;888888&#39;, &#39;1351111111&#39;], &#39;isonly&#39;: True}>>> type(person)<class &#39;dict&#39;# Python字典转换为json字符串>>> jsonStr = json.dumps(person) >>> print(jsonStr ){"name": "\u5c0f\u660e", "age": 30, "tel": ["888888", "1351111111"], "isonly": true}>>> type(jsonStr)<class &#39;str&#39;># json字符串再转换为Python字典>>> python_obj = json.loads(jsonStr)>>> print(python_obj){&#39;name&#39;: &#39;小明&#39;, &#39;age&#39;: 30, &#39;tel&#39;: [&#39;888888&#39;, &#39;1351111111&#39;], &#39;isonly&#39;: True}>>> print(type(python_obj))<class &#39;dict&#39;># 打印字典的所有key>>> print(python_obj.keys())  dict_keys([&#39;name&#39;, &#39;age&#39;, &#39;tel&#39;, &#39;isonly&#39;])

 # 打印字典的所有values>>> print(python_obj.values()) dict_values([&#39;小明&#39;, 30, [&#39;888888&#39;, &#39;1351111111&#39;], True])

文件操作:

import json

f = open(&#39;data.json&#39;, encoding=&#39;utf-8&#39;)content = f.read()  
# 使用loads()方法需要先读文件
python_obj = json.loads(content)print(python_obj)

输出结果:
"How

7、json.load()

从json格式的文件中读取数据并转换为python的类型。

语法格式json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

文件操作

import json

python_obj = json.load(open(&#39;data.json&#39;,&#39;r&#39;))print(python_obj)print(type(python_obj))

输出结果:
"How

json.load() json.loads() 区别:

  • loads() 传的是json字符串,而 load() 传的是文件对象

  • 使用 loads() 时需要先读取文件在使用,而 load() 则不用

8、总结

不管是dump还是load,带s的都是和字符串相关的,不带s的都是和文件相关的

三、XML文件和JSON文件互转

记录工作中常用的一个小技巧

cmd控制台安装第三方模块

pip install xmltodict

1、XML文件转为JSON文件

新建一个1.xml文件:

<note date="23/04/2022">
	<to>tom</to>
	<from>mary</from>
	<msg>love</msg></note>

"How

转换代码实现

import jsonimport xmltodictdef 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 = &#39;./1.xml&#39;  # xml文件的路径with open(XML_PATH, &#39;r&#39;) as f:
    xmlfile = f.read()
    with open(XML_PATH[:-3] + &#39;json&#39;, &#39;w&#39;) as newfile:
        newfile.write(xml_to_json(xmlfile))

输出结果(生成json文件):
"How

2、JSON文件转换为XML文件

新建test.json文件:

{
  "student": {
    "course": {
      "name": "math",
      "score": "90"
    },
    "info": {
      "sex": "male",
      "name": "name"
    },
    "stid": "10213"
  }}

"How

转换代码实现:

import xmltodictimport jsondef 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 = &#39;./test.json&#39;  # json文件的路径with open(JSON_PATH, &#39;r&#39;) as f:
    jsonfile = f.read()
    python_dict = json.loads(jsonfile)  # 将json字符串转换为python字典对象
    with open(JSON_PATH[:-4] + &#39;xml&#39;, &#39;w&#39;) as newfile:
        newfile.write(json_to_xml(python_dict))

输出结果(生成xml文件):
"How

json.dump(obj, fp)
json.loads(s)
json.load(fp)

The above is the detailed content of How to use Python's json standard library. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete