json | Python Standard Library – Real Python

The Python json module provides tools to encode and decode data in JavaScript Object Notation (JSON), a lightweight data interchange format that’s easy for humans to read and write and easy for machines to parse and generate.

Here’s a quick example:

Key Features

  • Serializes Python object to JSON strings
  • Deserializes JSON strings to Python objects
  • Supports complex data types with custom encoding and decoding

Frequently Used Classes and Functions

Object Type Description
json.dump() Function Serializes a Python object to a JSON-formatted stream
json.dumps() Function Serializes Python objects to a JSON-formatted string
json.load() Function Deserializes a JSON-formatted stream to a Python object
json.loads() Function Deserializes a JSON-formatted string to a Python object
json.JSONEncoder Class Provides a custom encoder for JSON serialization
json.JSONDecoder Class Provides a custom decoder for JSON deserialization

Examples

Serializing a Python dictionary to a JSON string:

Deserializing a JSON string to a Python dictionary:

Serializing with pretty printing:

Common Use Cases

  • Storing and exchanging data between a web server and a client
  • Configuring applications with JSON files
  • Logging structured data in a human-readable format

Real-World Example

You can use the json module to read configuration data from a JSON file and update it programmatically. Here’s an example of updating a user’s profile information stored in a JSON file:

This example demonstrates how you can use the json module to read, modify, and write JSON data to a file, facilitating tasks such as application configuration management.

Working With JSON Data in Python

For additional information on related topics, take a look at the following resources: