On this page
json.dumps
Prev: json.dump | Up: json | Next: json.JSONDecodeError
Rel: json.dump, json.JSONDecodeError, json.JSONDecoder, json.JSONEncoder
Ref: docs.python.org — json.dumps
Tags: #public #python3 #stdlib #json
Import
import json
from json import dumps
Signature & Overview
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.
Usage
import json
data = {"user": "Ada", "scores": [10, 20], "city": "Zürich"}
compact = json.dumps(data, separators=(",", ":"), ensure_ascii=False)
pretty = json.dumps(data, indent=2, sort_keys=True, ensure_ascii=False)
assert '"city":"Zürich"' in compact
assert "\n" in pretty
Gotchas
ensure_ascii=Trueis the default: Non-ASCII characters are escaped as\uXXXXunless you passensure_ascii=False.- Dictionary keys are coerced to strings: Integer keys like
{1: "a"}become{"1": "a"}and won't round-trip back tointkeys. - Custom types need
default=: Passdefault=stror a custom function to serializedatetime,UUID, orPathobjects.
REPL Inspect
from json import dumps
help(dumps)
Linked from
Related notes
- tuts/python3/stdlib_module/json/dump Linked here; links to this page; shared tags: #json, #stdlib
- tuts/python3/stdlib_module/json/JSONDecodeError Linked here; links to this page; shared tags: #json, #stdlib
- tuts/python3/stdlib_module/json/JSONDecoder Linked here; links to this page; shared tags: #json, #stdlib
- tuts/python3/stdlib_module/json/JSONEncoder Linked here; links to this page; shared tags: #json, #stdlib
- tuts/python3/stdlib_module/json Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/json/load links to this page; shared tags: #json, #stdlib
- tuts/python3/stdlib_module/json/loads links to this page; shared tags: #json, #stdlib
- tuts/c/stdlib shared tags: #stdlib
- tuts/c/stdlib/assert shared tags: #stdlib
- tuts/c/stdlib/assert/assert shared tags: #stdlib