API Navigator Logo

Using `json.dumps()` in Python

Author: Newtum

This example explains how to use the `json.dumps()` (dump string) method to serialize a Python object (like a dictionary or list) into a JSON formatted string.

Basic Serialization

`json.dumps()` converts a Python dictionary into a compact JSON string, which is ideal for sending data over a network.

import json

python_dict = {'name': 'Bob', 'age': 35, 'is_employed': True}

# Serialize the dictionary to a JSON string
json_string = json.dumps(python_dict)

print(type(json_string))
print(json_string)

Pretty-Printing with Indentation

You can make the output more readable by using the `indent` parameter. This is very useful for debugging and logging.

import json

python_dict = {'user': {'id': 123, 'name': 'Charlie'}, 'permissions': ['read', 'write']}

# Serialize with an indent of 2 spaces
pretty_json_string = json.dumps(python_dict, indent=2)

print(pretty_json_string)

Sorting Keys

For consistent output, especially for caching or comparisons, you can sort the keys in the JSON output using `sort_keys=True`.

import json

data = {'c': 3, 'a': 1, 'b': 2}

# Serialize with sorted keys
sorted_json = json.dumps(data, sort_keys=True, indent=2)

print(sorted_json)