JSON in Python uses the

Source: Internet
Author: User
Tags json serialization

This article mainly describes the use of JSON in Python, sample code based on the python2.x version, the need for friends can refer to the

JSON advanced

Python's Dict objects can be serialized directly into JSON {}, but many times we prefer to use class to represent objects, such as defining student classes, and then serializing:

?

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 = SC Ore s = Student (' Bob ', M.) Print (Json.dumps (s))

Run code, mercilessly get a typeerror:

?

1 2 3 Traceback (most recent call last): ... 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 even the instance object of class cannot be serialized as JSON, this is certainly unreasonable!

Don't worry, we'll take a closer look at the parameter list of the dumps () method, it is found that the dumps () method provides a large number of optional parameters in addition to the first required obj parameter:

Https://docs.python.org/2/library/json.html#json.dumps

These optional parameters allow us to customize the JSON serialization. The preceding code cannot serialize the student class instance to JSON because by default the dumps () method does not know how to change the student instance to a JSON {} object.

Optional parameter default is to turn any object into an object that can be serialized as JSON, and we just need to write a transformation function for student, and then pass the function in:

?

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=stude NT2DICT))

In this way, the student instance is first converted into dict by the student2dict () function and then 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 instances of class usually have a __dict__ attribute, it is a dict that stores instance variables. There are also a few exceptions, such as defining the __slots__ class.

Similarly, if we were 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 the student instance:

?

1 2 3 4 5 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:

?

1 <__main__. Student Object at 0x10cd3c190>

The student instance object that is being deserialized is printed.

Summary

The Python language-specific serialization module is pickle, but you can use the JSON module if you want to make serialization more generic and more compliant with web standards.

The dumps () and loads () functions of the JSON module are a good example of well-defined interfaces. When we use it, we only need to pass in a required parameter. However, when the default serialization or reverse sequence mechanism does not meet our requirements, we can pass in more parameters to customize the serialization or deserialization of the rules, both the interface is simple to use, but also to achieve full scalability and flexibility.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.