Course contentsShow
← Python
Lesson 384 of 1,0606. Error Handling and File I/OFree lesson

Serializing Python Objects with JSON

Learn to convert complex Python dictionaries and lists into standardized JSON format for platform-independent data storage and exchange.

In this lesson, you will learn how to convert your Python data structures into a standardized JSON format, enabling you to save and share your program's data across different platforms and applications.

Why Serialize?

While Python handles data like dictionaries and lists beautifully in memory, this data vanishes once your program stops running. Furthermore, other programming languages or web services cannot "read" a Python object directly. Serialization is the process of translating your Python data into a universal, text-based format called JSON (JavaScript Object Notation), which acts as a common language for software systems.

Turning Data into JSON

To perform this translation, Python provides the built-in json module. The primary function for serialization is json.dump(). This function takes two main arguments: the Python object you want to save, and an open file stream (which you should always manage using the with statement we learned earlier to ensure the file closes correctly).

Here is how you serialize a dictionary representing a user profile:

import json
from pathlib import Path

user_data = {
    "username": "coder_pro",
    "id": 42,
    "active": True,
    "roles": ["admin", "editor"]
}

# Define the file path safely
file_path = Path("user_settings.json")

# Serialize and write to a file
with open(file_path, "w") as file:
    json.dump(user_data, file, indent=4)

Key Considerations

When using json.dump(), the indent parameter is particularly useful. By setting indent=4, you add whitespace and line breaks to the output file, making the JSON "human-readable" rather than one giant, unformatted line of text.

Behind the scenes, the json module maps Python objects to their JSON equivalents. For example, a Python dict becomes a JSON object, a Python list becomes a JSON array, and True/False booleans are correctly converted to lowercase true/false. This creates a platform-independent snapshot of your data that is ready for storage or transmission.

Key Takeaway: Serialization uses the json.dump() function to convert Python objects into text-based JSON files, allowing your data to be stored persistently and read by any other application.