How to make python class JSON serializable?

205 viewsPython

How to make python class JSON serializable?

You are here because when you try to encode a custom Python object into a JSON format, you received a TypeError: Object of type SampleClass is not JSON serializable.

Farjanul Nayem Answered question December 13, 2022
0

The built-in json module of Python can only handle Python primitives types that have a direct JSON equivalent. i.e., The fundamental problem is that the JSON encoder json.dump() and json.dumps() only knows how to serialize the basic set of object types by default (e.g., dictionary, lists, strings, numbers, None, etc.). To solve this, we need to build a custom encoder to make our Class JSON serializable.

Sample Code:

import json
 class Employee(dict):
    def __init__(self, name, age, salary, address):
        dict.__init__(self, name=name, age=age, salary=salary, address=address)
 class Address(dict):
    def __init__(self, city, street, pin):
        dict.__init__(self, city=city, street=street, pin=pin)
 address = Address("Alpharetta", "7258 Spring Street", "30004")
employee = Employee("John", 36, 9000, address)
 print("Encode into JSON formatted Data")
employeeJSON = json.dumps(employee)
print(employeeJSON)
 # Let's load it using the load method to check if we can decode it or not.
print("Decode JSON formatted Data")
employeeJSONData = json.loads(employeeJSON)
print(employeeJSONData)

Output:

Encode into JSON formatted Data
{"name": "John", "age": 36, "salary": 9000, "address": {"city": "Alpharetta", "street": "7258 Spring Street", "pin": "30004"}}
 Decode JSON formatted Data
{'name': 'John', 'age': 36, 'salary': 9000, 'address': {'city': 'Alpharetta', 'street': '7258 Spring Street', 'pin': '30004'}}

Farjanul Nayem Answered question December 13, 2022
0
You are viewing 1 out of 1 answers, click here to view all answers.