JSON usage in Python
This article mainly introduces the use of JSON in Python. The sample code is based on Python2.x. For more information, see
JSON advanced
Python dict objects can be directly serialized into JSON {}. However, many times we prefer to use class to represent objects, such as defining the Student class, and then serialize:
?
1 2 3 4 5 6 7 8 9 10 |
Import json Class Student (object ): Def _ init _ (self, name, age, score ): Self. name = name Self. age = age Self. score = score S = Student ('bob', 20, 88) Print (json. dumps (s )) |
Run the code and get a TypeError without mercy:
?
1 2 3 |
Traceback (most recent call last ): ... TypeError: <__ main _. Student object at 0x10aabef50> is not JSON serializable |
The error occurs because the Student object is not a JSON object that can be serialized.
If the Instance Object of the class cannot be serialized as JSON, this is definitely unreasonable!
Don't worry. Let's take a closer look at the parameter list of the dumps () method. In addition to the first required obj parameter, the dumps () method also provides a lot of optional parameters:
Https://docs.python.org/2/library/json.html#json.dumps
These optional parameters allow us to customize JSON serialization. The previous Code failed to serialize the Student class instance to JSON because the dumps () method does not know how to change the Student instance to a JSON {} object by default.
The optional parameter default is to convert any object into a JSON object in sequence. We only need to write a conversion function for Student and then pass the function into it:
?
1 2 3 4 5 6 7 8 |
Def student2dict (std ): Return { 'Name': std. name, 'Age': std. age, 'Score ': std. score } Print (json. dumps (s, default = student2dict )) |
In this way, the Student instance is first converted to dict by the student2dict () function, and then serialized as JSON.
However, if you encounter a Teacher class instance next time, it cannot be serialized as JSON. We can steal the lazy and convert any class instance into dict:
Print (json. dumps (s, default = lambda obj: obj. _ dict __))
Generally, a class instance has a _ dict _ attribute, which is a dict used to store instance variables. There are also a few exceptions, such as the class that defines _ slots.
Similarly, if we want to deserialize JSON into a Student object instance, the loads () method first converts a dict object. Then, the input object_hook function converts dict to a Student instance:
?
1 2 3 4 5 |
Def dict2student (d ): Return Student (d ['name'], d ['age'], d ['score ']) Json_str = '{"age": 20, "score": 88, "name": "Bob "}' Print (json. loads (json_str, object_hook = dict2student )) |
The running result is as follows:
?
1 |
<__Main _. Student object at 0x10cd3c190> |
The output is a deserialized Student instance object.
Summary
The Python-specific serialization module is pickle, but if you want to make serialization more generic and more compliant with Web standards, you can use the json module.
The dumps () and loads () Functions of the json module are examples of well-defined interfaces. When using this function, you only need to input a required parameter. However, when the default serialization or deserialization mechanism does not meet our requirements, we can introduce more parameters to customize the serialization or deserialization rules, it not only makes the interface Easy to use, but also achieves full scalability and flexibility.