Python Glossary Русский

all Python 3jsonterm

json.JSONEncoder

classes

The class that encodes Python objects to JSON; override its default method to serialize unsupported types. json.dumps uses it internally.

Syntax

json.JSONEncoder().encode(obj)

In practice you rarely instantiate the encoder by hand — you subclass it and pass it as json.dumps(obj, cls=MyEncoder). default() is called only for values the encoder could not handle itself, and it must return something already serialisable (a dict, list, string), not a chunk of JSON text; for anything still unknown, call super().default(o) so a proper TypeError is raised. Note too that tuples come out as arrays and non-string dict keys are coerced to strings.

Examples

import json
print(json.JSONEncoder().encode([1, 2]))   # → [1, 2]
print(json.JSONEncoder().encode({'a': 1, 'b': None}))   # → {"a": 1, "b": null}
print(json.JSONEncoder(sort_keys=True).encode({'b': 2, 'a': 1}))   # → {"a": 1, "b": 2}
print(json.JSONEncoder().encode(range(3)))   # → TypeError
print(json.JSONEncoder(default=str).encode(range(3)))   # → "range(0, 3)"

See also

Open in the full glossarydocs.python.orgReport an inaccuracy