Python Glossary Русский

all Python 3jsonfunction

json.dumps

json

Serializes a Python object to a JSON string (dict, list, str, int, float, bool, None).

Syntax

json.dumps(obj, *, indent=None)

JSON keys are always strings: dumps({1: 'a'}) gives {"1": "a"}, and parsing it back leaves the key as a string — the original type is gone. Anything outside dict/list/tuple/str/int/float/bool/None (sets, datetime, Decimal, your own classes) raises TypeError; convert them via the default= hook. Note also that nan and inf come out as NaN/Infinity, which Python reads back but strict third-party parsers reject.

Examples

import json
print(json.dumps({'a': 1, 'b': [2, 3]}))   # → {"a": 1, "b": [2, 3]}
print(json.dumps([1, 2, 3]))                 # → [1, 2, 3]
print(json.dumps('привет', ensure_ascii=False))   # → "привет"
print(json.dumps({'b': 1, 'a': 2}, sort_keys=True))   # → {"a": 2, "b": 1}
print(json.dumps({1, 2}))   # → TypeError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy