Member-only story
How to Serialize a Class Object to JSON in Python
Serializing your own class objects is quite straightforward in Python. Here are some tips.
· 1. Class Definition
· 2. Requirements
· 3. Solutions
∘ Method 1: Use json.dumps() and __dict__
∘ Method 2: Implement __str__ and __repr__
∘ Method 3: Implement JSON Encoder
· 4. Handling complex objects
∘ Method 4: Implement to_json() method
∘ Method 5: Implement a custom to_json() method
· Conclusion
Serialization is the process of converting an object into a medium that can be saved and retrieved later: e.g., saving the state of an object into a file. For any mildly complex projects, serialization is something all developers have to do sooner or later. One of the nice things about the Python language is its ease of use in many common programming tasks. File IO, plotting diagrams, and accessing web contents are all easy with just a few lines of code. Serialization is also easy in Python, except when you are trying to serialize your own custom class. In this article, I want to share what I found to be the best practice in serializing your own class objects to JSON objects. The entire code sample is shared here.
1. Class Definition
Let‘s start with the definition of a sample class.
class Label:
def __init__(self, label, x, y, width, height):
self.label = label
self.x = x
self.y = y
self.width = width
self.height = heightIf you want to serialize (e.g., to print out the object), you will get an esoteric message like this:
label = Label("person", 10, 10, 4, 10)
print(label)>> <__main__.Label object at 0x000002C3913EB2E0>
Python JSON library provides a handy method called json.dumps() to turn any Python objects into JSON. This is good so you call the method and pass the object. It sounds simple so let’s do that.
import json
print(json.dumps(label))>>...
/usr/lib/python3.7/json/encoder.py in default(self, o)…
