json.dumps
json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)Serialize obj to a JSON formatted str. The default encoder supports dict, list, tuple, str, int, float, bool, and None.
| Parameter | Description |
|---|---|
obj | The Python object to encode. |
ensure_ascii | If True (the default), non-ASCII characters are escaped as \uXXXX. |
sort_keys | If True, object keys are sorted in the output. This argument exists only on the encoder. |
indent | If a non-negative integer, pretty-print with that many spaces of indentation. None selects the most compact representation. |
separators | A (item_separator, key_separator) tuple. The compact default is (", ", ": "); (",", ":") removes extra spaces. |
default | A function called for objects the encoder does not support. If it cannot convert the object, it should raise TypeError. |
allow_nan | If True (the default), NaN, Infinity, and -Infinity are encoded as non-standard JSON tokens. If False, those values raise ValueError. |
skipkeys | If True, skip dict keys that are not basic types instead of raising TypeError. |
check_circular | If True (the default), a circular reference raises ValueError instead of overflowing the stack. |
Returns: A str containing JSON text. json.dump() writes to fp and returns None.
Raises
TypeError— Raised for unsupported types such as set, or for a dict key that is not a basic type when skipkeys is False.ValueError— Raised for circular references when check_circular is True, and for out-of-range floats when allow_nan is False. This is not JSONDecodeError.
- Dict keys are coerced to strings in the output. json.dumps({1: "x"}) returns '{"1": "x"}'. sort_keys=True still compares the original key objects, so mixing int and str keys raises TypeError.
- datetime, bytes, and set values are not JSON-serializable unless you supply default= or a custom encoder class.
import json
import math
print(json.dumps({"city": "München"}))
print(json.dumps({"city": "München"}, ensure_ascii=False))
print(json.dumps({1: "x"}))
print(json.dumps({"b": 2, "a": 1}, sort_keys=True, separators=(",", ":")))
try:
json.dumps({"port": math.nan}, allow_nan=False)
except ValueError as exc:
print(type(exc).__name__)
try:
json.dumps({"tags": {"alpha", "beta"}})
except TypeError as exc:
print(type(exc).__name__)Expected output
{"city": "M\u00fcnchen"}
{"city": "München"}
{"1": "x"}
{"a":1,"b":2}
ValueError
TypeErrorRelated: JSON Diff tool, json.loads, Normalize JSON before a text diff