Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to serialize class objects into JSON in Python

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article is a detailed introduction to "how to serialize class objects into JSON in Python". The content is detailed, the steps are clear, and the details are properly handled. I hope this article "how to serialize class objects into JSON in Python" can help you solve your doubts. Let's go deeper and learn new knowledge together with the ideas of Xiaobian.

1. introduction

Serialization is the process of converting objects into media that can be saved and retrieved later. For example, save the current state of an object to a file. For some complex projects, serialization is something all developers do sooner or later.

One of the advantages of Python is that it is easy to use for many common programming tasks, often with just a few lines of code, reading file IO, drawing diagrams, etc. Serialization is also very easy to implement in Python.

2. give a chestnut

To illustrate the tricks of serialization, let's first define a class as an example,

The code is as follows:

class LabelSimple:def __init__(self, label, x, y, width, height):self.label = labelself.x = xself.y = yself.width = widthself.height = height

If we try to serialize it (e.g. print the object of the class directly), we will get the following error message:

label = LabelSimple("person", 10, 10, 4, 10)print(label)>> __main__.LabelSimple object at 0x000002C3913EB2E0>

The JSON library in Python provides a convenient method called json.dumps(). It can convert any Python object to JSON. This sounds simple enough, so let's try it out directly.

import jsonprint(json.dumps(label))>>.../ usr/lib/python3.7/json/encoder.py in default(self, o)177178 """--> 179 raise TypeError(f'Object of type {o.__ class__.__ name__} '180 f'is not JSON serializable')181TypeError: Object of type LabelSimple is not JSON serializable

json.dumps() calls the appropriate encoder for our custom object and raises a class object error because we don't implement an encoder.

3. Solution 3.1 Using json.dumps() and__dict__

The easiest way to serialize the above class objects directly for export is to use the built-in__dict__method to display the object's contents.

The code is as follows:

label = Label("person", 10, 10, 4, 10)print(label.__ dict__)print(json.dumps(label.__ dict__))

The output is as follows:

{"label": "person", "x": 10, "y": 10, "width": 4, "height": 10}

{"label": "person", "x": 10, "y": 10, "width": 4, "height": 10}

As you can see, the print() function and json.dumps() function output the contents of the class object in JSON format using the above method.

3.2 implement__str__and__repr__

Although the above implementation can achieve the purpose of serialization, we need to call the__dict__method every time, which is somewhat troublesome. We can also have a simpler way to implement the class built-in functions__str and__repr__,

The code is as follows:

class Label:def __init__(self, label, x, y, width, height):self.label = labelself.x = xself.y = yself.width = widthself.height = heightdef __iter__(self):yield from {"label": self.label,"x": self.x,"y": self.y,"width": self.width,"height": self.height}.items()def __str__(self):return json.dumps(dict(self), ensure_ascii=False)def __repr__(self):return self.__ str__()

The call code is as follows:

label = Label("person", 10, 10, 4, 10)print(label)# print(json.dumps(label))

The above code, print, can output serialized JSON content, but json.dumps still doesn't work because we don't implement encoder.

3.3 Implementation of JSON encoder

To support the json.dumps use case, a common approach is to implement custom encoder classes by inheriting JSONEncoder. In the above example, since we want the object to be in JSON dictionary format, we just return the dictionary.

The code is as follows:

from json import JSONEncoderclass MyEncoder(JSONEncoder):def default(self, obj):return obj.__ dict__label = Label("person", 10, 10, 4, 10)print(MyEncoder().encode(label))print(json.dumps(label, cls=MyEncoder))print(label)

The output is as follows:

# outputs of a Label class object

{"label": "person", "x": 10, "y": 10, "width": 4, "height": 10}

{"label": "person", "x": 10, "y": 10, "width": 4, "height": 10}

{"label": "person", "x": 10, "y": 10, "width": 4, "height": 10}

Read here, this article "How to serialize class objects into JSON in Python" has been introduced, want to master the knowledge points of this article also need to be used by yourself to understand, if you want to know more about the relevant content of the article, welcome to pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report