Python Function Reference

json.dumps

Convert a Python object to a JSON string.

Python 3.13
json.dumps(obj, *, ensure_ascii=True, indent=None, sort_keys=False)

Parameters

objAny
The object to convert: a dict, list, tuple, string, number, bool or None.
ensure_asciibooloptional
If False, non-ASCII characters are written as is instead of \uXXXX escapes.
indentint | str | Noneoptional
The indentation for nested items; if given, the JSON spans several lines.
sort_keysbooloptional
If True, dictionary keys are sorted.

Return value

A string with JSON; raises TypeError for an unsupported object such as a set.

Examples

Dictionary to a JSON string

Python 3.13
import json

print(json.dumps({'name': 'Anna', 'age': 25, 'admin': False}))
{"name": "Anna", "age": 25, "admin": false}

Cyrillic text without escaping

Python 3.13
import json

print(json.dumps({'city': 'Москва'}, ensure_ascii=False))
{"city": "Москва"}

Indentation and sorted keys

Python 3.13
import json

print(json.dumps({'b': 1, 'a': [1, 2]}, indent=2, sort_keys=True))
{
  "a": [
    1,
    2
  ],
  "b": 1
}

Details

True, False and None become true, false and null, and tuples become lists. JSON keys can only be strings: number keys, True, False and None are converted to strings ("1", "true", "null"), while a key of another type, such as a tuple, raises TypeError. The function has other keyword parameters too, such as separators and default.

See also

Where to learn