Skip to content

JSON serialization in Python

JSON serialization in Python is the process of converting Python dictionaries into JSON formatted strings for storage or transmission.^[400-devops-09-scripting-language-python-introduction-part-3json-readme.md] This is a standard practice for data persistence, configuration files, and communication between applications via HTTP Web APIs.^[400-devops-09-scripting-language-python-introduction-part-3json-readme.md]

The json Library

Python provides a built-in json library to handle these operations^[400-devops-09-scripting-language-python-introduction-part-3json-readme.md].

  • json.dumps(data): This function (short for "dump string") serializes a Python dictionary into a JSON formatted string^[400-devops-09-scripting-language-python-introduction-part-3json-readme.md].
  • json.loads(data): This function deserializes a JSON string back into a Python dictionary^[400-devops-09-scripting-language-python-introduction-part-3json-readme.md].

Object Serialization Constraints

The json.dumps() function can only natively handle data structures consisting of standard Python dictionaries and primitives^[400-devops-09-scripting-language-python-introduction-part-3json-readme.md].

If a dictionary contains custom class instances, attempting to serialize it will raise a TypeError: Object of type [ClassName] is not JSON serializable^[400-devops-09-scripting-language-python-introduction-part-3json-readme.md].

To serialize custom objects, you must first convert the object into a standard dictionary representation^[400-devops-09-scripting-language-python-introduction-part-3json-readme.md]. A common technique is to access the object's __dict__ attribute, which exposes the object's properties as a dictionary^[400-devops-09-scripting-language-python-introduction-part-3json-readme.md].

For example, converting a Customer object: customerDict[id] = customers[id].__dict__^[400-devops-09-scripting-language-python-introduction-part-3json-readme.md]

File Workflow

A typical workflow involves reading data from a JSON file into a Python dictionary, manipulating the data, and writing it back^[400-devops-09-scripting-language-python-introduction-part-3json-readme.md].

Reading (Deserialization): 1. Open the file. 2. Read the string content. 3. Use json.loads() to convert the string into a working dictionary^[400-devops-09-scripting-language-python-introduction-part-3json-readme.md].

Writing (Serialization): 1. Open the file in write mode. 2. Use json.dumps() on the dictionary to create a JSON string. 3. Write the string to the file^[400-devops-09-scripting-language-python-introduction-part-3json-readme.md].

  • File I/O
  • [[Dictionaries]]
  • [[Python Class]]

Sources

^[400-devops-09-scripting-language-python-introduction-part-3json-readme.md]