Skip to content

JSON serialization with __dict__

JSON serialization with __dict__ is a technique in Python used to convert custom class instances into JSON-compatible strings by leveraging the object's internal attribute dictionary.^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md]

Standard Python JSON serialization functions, such as those found in the json module, handle native types like dictionaries, lists, and strings automatically^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md]. However, they cannot natively process custom user-defined classes; attempting to pass a class instance directly to json.dumps results in a TypeError: Object of type [ClassName] is not JSON serializable^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md].

To bridge this gap, the __dict__ attribute is used to transform the object into a standard dictionary format that the json module understands^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md].

How it works

The __dict__ attribute in Python holds a writable representation of an object's attributes (the instance variables) and their values. By accessing object.__dict__, the instance is effectively converted into a standard dictionary where keys are attribute names and values are the associated data^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md].

For example, a Customer class with attributes like customerID, firstName, and lastName can be converted into a dictionary representation:

# Original object
customer = Customer("i", "Bob", "Smith")

# Conversion using __dict__
customer_dict = customer.__dict__
# Result: {'customerID': 'i', 'firstName': 'Bob', 'lastName': 'Smith'}

This dictionary can then be safely processed by the json library^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md].

Usage example

In a typical workflow, such as managing a collection of customer objects, __dict__ is used to serialize the data for storage or transmission^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md].

1. Manual Iteration

When converting a dictionary of objects (e.g., {"a": Customer(...)}), a new dictionary must be constructed where the values are converted via __dict__^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md].

# Assuming 'customers' is a dict of Customer objects
customer_dict = {}
for id in customers:
    customer_dict[id] = customers[id].__dict__

# Serialize the new dictionary
json_data = json.dumps(customer_dict)

2. Adding New Entries

This method also facilitates adding new entries to an existing dataset. A new instance can be serialized on the fly before being added to the collection^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md].

customers["i"] = Customer("i", "Bob", "Smith").__dict__
  • [[JSON]]
  • [[Python]]
  • [[Serialization]]
  • [[Docker]]

Sources

  • 400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md