How to Pretty Print JSON in JavaScript, Python, Go and the Command Line
· 4 min read
To pretty print JSON, parse it and serialize it again with indentation: JSON.stringify(obj, null, 2) in JavaScript, json.dumps(obj, indent=2) in Python, json.MarshalIndent(v, "", " ") in Go, and jq . or python3 -m json.tool on the command line. For a one-off paste, the JSON formatter does the same in your browser without uploading anything.
Quick reference
| Where | Pretty print | Sort keys | Minify |
|---|---|---|---|
| JavaScript | JSON.stringify(v, null, 2) | No built-in option | JSON.stringify(v) |
| Python | json.dumps(v, indent=2) | sort_keys=True | separators=(",", ":") |
| Go | json.MarshalIndent(v, "", " ") | Maps are sorted automatically | json.Compact or json.Marshal |
| jq | jq . file.json | jq -S . | jq -c . |
| Python CLI | python3 -m json.tool file.json | --sort-keys | --compact |
JavaScript and Node.js
const data = { name: "Ada", langs: ["en", "fr"], active: true };
JSON.stringify(data, null, 2); // 2 spaces
JSON.stringify(data, null, "\t"); // tabs
// Pretty print a JSON string you received
const pretty = JSON.stringify(JSON.parse(text), null, 2);
// Sorted keys (recursive)
const sortKeys = (v) =>
Array.isArray(v) ? v.map(sortKeys)
: v && typeof v === "object"
? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sortKeys(v[k])]))
: v;
JSON.stringify(sortKeys(data), null, 2);The third argument accepts a number (capped at 10 spaces) or a string. In the browser console, console.log(obj) already shows an expandable tree; console.log(JSON.stringify(obj, null, 2)) gives copyable text. In Node, console.dir(obj, { depth: null }) prints nested objects fully instead of [Object].
JSON.parse converts numbers to doubles, so integers above 2^53 (9007199254740992) are rounded when you reformat this way. A formatter that preserves the original digits, like the JSON formatter here, avoids changing large IDs.
Python
import json
data = {"name": "Zoë", "langs": ["en", "fr"], "active": True}
print(json.dumps(data, indent=2))
print(json.dumps(data, indent=2, sort_keys=True))
print(json.dumps(data, indent=2, ensure_ascii=False)) # keep "Zoë" instead of "Zo\u00eb"
# Write a pretty file
with open("out.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
f.write("\n")pprint.pprint prints Python repr (single quotes, True), which is not valid JSON; use json.dumps when you need JSON output. Python keeps large integers exact, unlike JavaScript.
Go
package main
import (
"bytes"
"encoding/json"
"fmt"
"os"
)
func main() {
v := map[string]any{"name": "Ada", "langs": []string{"en", "fr"}}
out, _ := json.MarshalIndent(v, "", " ")
fmt.Println(string(out))
// Re-indent raw JSON bytes without decoding into a struct
raw := []byte(`{"b":1,"a":[1,2]}`)
var buf bytes.Buffer
if err := json.Indent(&buf, raw, "", " "); err != nil {
fmt.Fprintln(os.Stderr, err)
}
fmt.Println(buf.String())
}encoding/json writes map keys in sorted order, while struct fields keep their declaration order. json.Indent keeps the original key order and number text, which makes it the safest choice for reformatting JSON you did not produce. It also escapes <, > and & by default when marshaling; use an Encoder with SetEscapeHTML(false) if that bothers you.
Command line
# jq: pretty, colored in a terminal
jq . data.json
curl -s https://api.github.com/repos/jqlang/jq | jq .
jq --indent 4 . data.json # 4 spaces
jq --tab . data.json # tabs
jq -S . data.json # sort keys
jq -c . data.json # minify to one line
# No jq installed? Python ships with a formatter
python3 -m json.tool data.json
python3 -m json.tool --sort-keys --indent 4 data.json
# Reformat a file in place (write to a temp file first)
jq . data.json > tmp.json && mv tmp.json data.jsonNever redirect into the file you are reading (jq . f.json > f.json): the shell truncates it before jq reads it and you lose the data. For very large files, jq's --stream mode or a viewer built for size is more practical; see how to open huge JSON files.
Editors
- VS Code: open a
.jsonfile and run Format Document (Shift+Alt+F on Windows, Shift+Option+F on macOS, Ctrl+Shift+I on Linux). - JetBrains IDEs: Reformat Code (Ctrl+Alt+L, or Option+Command+L on macOS).
- Vim:
:%!jq .pipes the buffer through jq.
When it fails to format
Every method above parses first, so invalid JSON stops with an error such as Unexpected token or Expecting property name enclosed in double quotes. Common causes are trailing commas, single quotes and comments; the common JSON errors guide explains each one, and the JSON fixer repairs them with a reviewable diff.
FAQ
How do I pretty print JSON in JavaScript?
Use JSON.stringify(value, null, 2). If you have a JSON string, parse it first: JSON.stringify(JSON.parse(text), null, 2).
How do I pretty print JSON in Python?
Use json.dumps(data, indent=2). Add sort_keys=True to sort keys and ensure_ascii=False to keep non-ASCII characters readable.
How do I pretty print JSON in the terminal?
Pipe it to jq ., or use python3 -m json.tool file.json if jq is not installed.
What is the difference between pretty print and minify?
Pretty printing adds line breaks and indentation for humans; minifying removes all optional whitespace to make the payload smaller. Both represent the same data. Try the minifier to compare.
Does pretty printing change my data?
It should not change values, but tools that parse into native numbers can round very large integers. Tools that reformat text, like Go's json.Indent, keep the original digits.

