Detailed usage introduction of json serialization - python tutorial

Python's built-in json module provides very sophisticated object-to-JSON conversion. Without further ado, let's take a look at how to turn a Python object into a JSON:

d = dict(name='Kaven', age=17, sex='Male')
print(json.dumps(d))  # {"name": "Kaven", "age": 17, "sex": "Male"}

Description:
The dumps() method returns a str whose content is standard JSON. Similarly, the dump() method can directly write JSON to an Object.
To deserialize JSON into a Python object, we can use loads() or the corresponding load() method. The former deserializes JSON strings, and the latter reads strings from Object and deserializes them:

For example:

import json
json_str = '{"name": "Kaven", "age": 17, "sex": "Male"}'
print(json.loads(json_str)) # {'name': 'Kaven', 'age': 17, 'sex': 'Male'}

Python's dict object can be directly serialized to JSON {}, so how to use class object, such as defining the Person class, and then serializing it?

The optional parameter default of dumps is to turn any object into an object that can be serialized as JSON. We only need to write a conversion function for Person, and then pass the function in:

import json


class Person(object):
    # __slots__ = ('name', 'age') # 通常class的实例都有一个__dict__属性,它就是一个dict,
    # 用来存储实例变量。也有少数例外,比如定义了__slots__的class,大家可以开启后运行看看报错信息
    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex


def PersonToDict(cls):
    return {
        'name': cls.name,
        'age': cls.age,
        'sex': cls.sex
    }


s = Person('Kaven', 17, 'Male')
print(json.dumps(s, default=PersonToDict))
# print(json.dumps(s, default=lambda obj: obj.__dict__)) 输出和上面一样
# 输出 : {"name": "Kaven", "age": 17, "sex": "Male"}

In this way, the Person instance is first converted into a dict by the PersonToDict() function, and then serialized into JSON. You can see that there is a lambda anonymous function below, which is very useful, such as:

Next time if you encounter an instance of a class such as Apple/Banaba, you can turn the instance of any class into a dict:

print(json.dumps(s, default=lambda obj: obj.__dict__)) # obj为对象参数名,可自定义

In the same way, if we want to deserialize JSON into a Person object instance, the loads() method first converts a dict object, and then the object_hook function we pass in is responsible for converting the dict to a Person instance:

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import json

class Person(object):
    # __slots__ = ('name', 'age') # 通常class的实例都有一个__dict__属性,它就是一个dict,
    # 用来存储实例变量。也有少数例外,比如定义了__slots__的class,大家可以开启后运行看看报错信息
    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex


def DictToPerson(d):
    return Person(d['name'], d['age'], d['sex'])

json_str = '{"name": "Kaven", "age": 20, "sex": "Male"}'
cls = json.loads(json_str, object_hook=DictToPerson)
print(cls.name) # Kaven

Python also has a pickle module, which may have Python compatibility problems, and only use Pickle to save those unimportant data

Guess you like

Origin blog.csdn.net/m0_67575344/article/details/123907862