Brief introduction to JSON usage in Python

Source: Internet
Author: User
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:

import jsonclass Student(object):  def __init__(self, name, age, score):    self.name = name    self.age = age    self.score = scores = Student('Bob', 20, 88)print(json.dumps(s))

Run the code and get a TypeError Without Mercy:

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:

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:

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:

<__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.

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.