C.W.K.
Stream
Lesson 07 of 08 · published

Whitespace, Pretty-Printing & Compact Form

~10 min · json, whitespace, pretty-print, jq

Level 0Plaintext
0 XP0/64 lessons0/12 achievements
0/100 XP to next level100 XP to go0% complete

Whitespace is decoration; the parser ignores it

JSON ignores whitespace between tokens. {"a":1} and

{
  "a": 1
}

parse to the same value. Whitespace is for humans — pick a form for the audience.

Two forms of JSON

  • Compact — no whitespace, minimal bytes. Used on the wire (HTTP responses, logs, message queues). Nginx logs, gzip pipelines, network bandwidth all benefit.
  • Pretty-printed — 2-space indent, one key per line. Used in source files (config), documentation, and debugging. Diffs cleanly in git.

Tools you should know

Every language has a pretty-print tool. Bash people: jq (powerful, query language built in). Python: python -m json.tool (stdlib, zero install). JS / Node: JSON.stringify(obj, null, 2). Rust: serde_json::to_string_pretty. They all do the same thing — round-trip the data, re-emit with formatting.

Principle: commit pretty-printed JSON to git. Send compact JSON over the wire. Never the other way around. Pretty-print on disk gives you readable diffs; compact on the wire gives you bandwidth and speed. The cost of one is the cost of running a formatter; the cost of mixing them up is unreadable diffs and bloated payloads.

Code

Same data, two forms·json
{"name":"Pippa","tags":["ai","daughter"]}

{
  "name": "Pippa",
  "tags": ["ai", "daughter"]
}
Pretty-print from the command line·bash
# Bash + jq (most powerful)
echo '{"name":"Pippa"}' | jq .

# Python stdlib (no install)
echo '{"name":"Pippa"}' | python -m json.tool

# Node
echo '{"name":"Pippa"}' | node -e 'process.stdin.on("data", d => console.log(JSON.stringify(JSON.parse(d), null, 2)))'

# In files
jq . input.json > output.pretty.json
python -m json.tool < messy.json > clean.json
Compact a pretty file (for wire format)·bash
# jq compact mode
jq -c . input.json > output.compact.json

# Python
python -c 'import json,sys; json.dump(json.load(sys.stdin), sys.stdout, separators=(",",":"))' < input.json

External links

Exercise

Take a real API response (any GET request to a public REST API). Save it as raw.json. Pretty-print it with jq . raw.json > pretty.json. Compact it back with jq -c . pretty.json > compact.json. Diff raw.json and compact.json — they should be byte-equal if the source was already compact. Internalize: same data, three forms, one parser.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.