Home  >  Article  >  Backend Development  >  Python summary of json standard library

Python summary of json standard library

WBOY
WBOYforward
2022-04-26 17:58:412703browse

This article brings you relevant knowledge about python, which mainly introduces related issues about the json standard library, including a basic overview of JSON, json modules, XML files and JSON file interaction Let’s take a look at the transferred content below. I hope it will be helpful to everyone.

Python summary of json standard library

Recommended learning: python video tutorial

1. Overview of JSON basics

1. What is JSON?

JSON (Full name: JavaScript Object N otation object representation) is a lightweighttextdataexchange format. The data format of JSON is actually the dictionary format in Python, which can contain An array enclosed in square brackets is a list in Python.

  • JSONLanguage independent
  • JSON is self-descriptive and easier to understand
  • JSON is more ## than XML ##Small, morefast, moreeasy to parse
  • Crawlers often obtain interface data, which is in JSON format
2. What does JSON 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 json key-value pair must be wrapped in double quotes ". Single quotes will not work (so if keywords appear in the key, they will also be characterized). There are no mandatory requirements for objects in js (so keywords are not allowed in keys).

2. The

value part of the json key-value pair does not allow functions, undefined, NaN, but can have null, which can appear in the value of the object in js.

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, it is not allowed.

4, json format summary

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 incorrect json format is as follows:

Python summary of json standard library

二, json module

1. Function

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

2. From python object Format it into an ison string (dump)

2. Data type conversion

Convert the data from

Python to json format. There will be changes in the data type, as follows The table shows:

PythonJSON##dictlist, tuple##strstringint, float, int- & float-derived Enumsnumbertruefalsenull In turn, convert the json format into python built-in types, as shown in the following table:
object
array
##True
False
None

JSONPythonobjectdictliststrintfloat##trueTruefalseFalsenullNoneThe use of the json module is actually very simple, for most occasions Next, we only need to use the following four methods:
array
string
number(int)
number(real)
3. Usage method

Method

Functionjson.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)
>> jsonStr = json.dumps(person) 
>>> print(jsonStr )
{"name": "\u5c0f\u660e", "age": 30, "tel": ["888888", "1351111111"], "isonly": true}
>>> type(jsonStr)

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

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

>>> print(json.dumps(person, sort_keys=True, indent=4, separators=(',', ': '))){
    "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=('!', '-'))){
    "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('test.json', 'w', encoding='utf-8') as f:  # 打开文件
    f.write(jsonStr)  # 在文件里写入转成的json串

查看生成的新文件:
Python summary of json standard library

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('data.json', 'w'))

查看生成的新文件:
Python summary of json standard library
使用参数能让JSON字串格式化输出:

import json

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

再次查看文件:
Python summary of json standard library
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){'name': '小明', 'age': 30, 'tel': ['888888', '1351111111'], 'isonly': True}>>> type(person)>> jsonStr = json.dumps(person) >>> print(jsonStr ){"name": "\u5c0f\u660e", "age": 30, "tel": ["888888", "1351111111"], "isonly": true}>>> type(jsonStr)# json字符串再转换为Python字典>>> python_obj = json.loads(jsonStr)>>> print(python_obj){'name': '小明', 'age': 30, 'tel': ['888888', '1351111111'], 'isonly': True}>>> print(type(python_obj))# 打印字典的所有key>>> print(python_obj.keys())  dict_keys(['name', 'age', 'tel', 'isonly'])

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

文件操作:

import json

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

输出结果:
Python summary of json standard library

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('data.json','r'))print(python_obj)print(type(python_obj))

输出结果:
Python summary of json standard library

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文件:


	tom
	mary
	love

Python summary of json standard library

转换代码实现

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 = './1.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))

输出结果(生成json文件):
Python summary of json standard library

2、JSON文件转换为XML文件

新建test.json文件:

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

Python summary of json standard library

转换代码实现:

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 = './test.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))

输出结果(生成xml文件):
Python summary of json standard library

推荐学习:python视频教程

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

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

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