← All languages
Python function of the day
Random

json.dumps

Serialize a Python object to a JSON formatted string.

Description

The json.dumps() function serializes a Python object into a JSON formatted string. It is part of the json standard library module and supports common Python types including dicts, lists, strings, numbers, booleans, and None.

The function provides many formatting options: indent for pretty-printing, sort_keys for deterministic output, separators for compact encoding, and default for handling non-serializable objects. The ensure_ascii parameter controls whether non-ASCII characters are escaped.

json.dumps() is fundamental for web APIs, configuration files, data serialization, and inter-process communication. It pairs with json.loads() for round-trip serialization. For writing directly to a file, use json.dump() instead.

Arguments

NameDescriptionOptional
obj The Python object to serialize. No
indent Number of spaces for pretty-printing indentation. Yes
sort_keys If True, output dictionaries sorted by key. Yes
default A function called for non-serializable objects. Yes

Example

import json
json.dumps({'name': 'Alice', 'age': 30})  # Returns '{"name": "Alice", "age": 30}'
json.dumps([1, 2, 3], indent=2)  # Pretty-printed JSON array

Reference