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)
  • =default value
  • *arguments after it by name only
obj
The object to convert: a dict, list, tuple, string, number, bool or None.
Any
ensure_ascii
If False, non-ASCII characters are written as is instead of \uXXXX escapes.
boolOptional
indent
The indentation for nested items; None by default, which puts everything on one line.
int | str | NoneOptional
sort_keys
If True, dictionary keys are sorted.
boolOptional

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