json.dumps Controls Indent, Keys And Separators

indent renders readable trees, compact separators squeeze bytes onto one line, and sort_keys makes equal dicts serialize byte-identically.

PythonData Integrity

Code

pythonsnippet
19 lines
import json

settings = {
    "zlib_level": 6,
    "cache": {"ttl": 300, "enabled": True},
    "tags": ["edge", "eu"],
    "owner": "platform team",
}

# indent=2 renders a readable tree that diffs line by line.
print(json.dumps(settings, indent=2))

# Compact separators squeeze out whitespace: one line, minimal bytes.
compact = json.dumps(settings, separators=(",", ":"))
print(compact)

# sort_keys fixes key order, so equal dicts serialize identically.
canonical = json.dumps(settings, sort_keys=True, separators=(",", ":"))
print(canonical)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

{
  "zlib_level": 6,
  "cache": {
    "ttl": 300,
    "enabled": true
  },
  "tags": [
    "edge",
    "eu"
  ],
  "owner": "platform team"
}
{"zlib_level":6,"cache":{"ttl":300,"enabled":true},"tags":["edge","eu"],"owner":"platform team"}
{"cache":{"enabled":true,"ttl":300},"owner":"platform team","tags":["edge","eu"],"zlib_level":6}

How it works

The demo data lives in module-level bindings: settings, compact, canonical.

Watch out for

  • The dependency list is empty; the language runtime covers it all.

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `settings`, `compact`, `canonical`.