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.
Code
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
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.