JSON Advanced
Python's Dict object can be serialized directly into the JSON {}, but, many times, we prefer to use class to represent objects, such as defining the student class, and then serializing:
Import Jsonclass Student (object): def __init__ (self, name, age, score): self.name = name self.age = Age Self.score = scores = Student (' Bob ', ', ') print (Json.dumps (s))
Run the code and relentlessly get a typeerror:
Traceback (most recent): ... TypeError: <__main__. Student object at 0x10aabef50> was not JSON serializable
The reason for the error is that the student object is not an object that can be serialized as JSON.
If the instance object of a class cannot be serialized as JSON, this is certainly unreasonable!
Don't worry, let's take a closer look at the parameter list of the dumps () method, you can see that the dumps () method provides a whole bunch of optional parameters in addition to the first required obj parameter:
Https://docs.python.org/2/library/json.html#json.dumps
These optional parameters are for us to customize JSON serialization. The previous code was unable to serialize the student class instance to JSON because, by default, the dumps () method did not know how to make the student instance a JSON {} object.
Optional parameter The default is to turn any object into an object that can be serialized as JSON, we just need to write a conversion function for student, and then pass the function in:
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 successfully serialized into JSON.
However, the next time you encounter an instance of a teacher class, you cannot serialize to JSON. We can steal a lazy, turn an instance of any class into dict:
Print (Json.dumps (s, Default=lambda obj:obj.__dict__))
Because an instance of class usually has a __dict__ property, it is a dict that stores instance variables. There are a few exceptions, such as defining the class of __slots__.
Similarly, if we want to deserialize JSON into a student object instance, the loads () method first converts a Dict object, and then the Object_hook function we pass in is responsible for converting dict to student instance:
def dict2student (d): return Student (d[' name '], d[' age '), d[' score ']) Json_str = ' {' Age ': $, ' score ': "," "Name": "Bob "} ' Print (Json.loads (JSON_STR, object_hook=dict2student))
The results of the operation are as follows:
<__main__. Student Object at 0x10cd3c190>
Prints out the student instance object that was deserialized.
Summary
Python language-specific serialization modules are pickle, but if you want to make serialization more generic and Web-compliant, you can use a JSON module.
The dumps () and loads () functions of the JSON module are examples of well-defined interfaces. When we use it, we only need to pass in a required parameter. However, when the default serialization or deserialization mechanism does not meet our requirements, we can also pass in more parameters to customize the serialization or deserialization rules, not only the interface is simple to use, but also to achieve full scalability and flexibility.