Pretty Printing JSON in JavaScript
JavaScript has built-in support for pretty printing JSON through theJSON.stringify() method. The third argument, called the space parameter, controls indentation:
// Pretty print an object
const data = { name: 'Alice', scores: [98, 87, 92] };
console.log(JSON.stringify(data, null, 2));
// {
// "name": "Alice",
// "scores": [
// 98,
// 87,
// 92
// ]
// }
// Pretty print a raw JSON string (re-format)
const raw = '{"x":1,"y":2}';
console.log(JSON.stringify(JSON.parse(raw), null, 2));
// With tab indentation
console.log(JSON.stringify(data, null, '\t'));
// Pretty print to a file in Node.js
const fs = require('fs');
fs.writeFileSync('output.json', JSON.stringify(data, null, 2));
// Replacer function — filter keys or transform values before pretty printing
const filtered = JSON.stringify(data, (key, value) => {
if (key === 'privateField') return undefined; // exclude this key
return value;
}, 2);Pretty Printing JSON in Python
import json
# Pretty print a Python dict
data = {"name": "Alice", "scores": [98, 87, 92]}
print(json.dumps(data, indent=2))
# Pretty print a JSON string
raw = '{"x":1,"y":2}'
print(json.dumps(json.loads(raw), indent=2))
# Sort keys alphabetically while pretty printing
print(json.dumps(data, indent=2, sort_keys=True))
# Preserve Unicode characters (don't escape to \uXXXX)
data_unicode = {"greeting": "こんにちは", "city": "東京"}
print(json.dumps(data_unicode, indent=2, ensure_ascii=False))
# Read a file, pretty print, write to another file
with open('raw.json') as f:
data = json.load(f)
with open('pretty.json', 'w') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
# One-liner from command line:
# python3 -m json.tool raw.jsonPretty Printing JSON from the Command Line
# ── jq (recommended) ──────────────────────────────────────────────────
# Install: brew install jq (Mac), apt install jq (Ubuntu)
# Pretty print a file
jq . data.json
# Pretty print curl response
curl -s https://api.github.com/users/octocat | jq .
# Extract a specific field and pretty print
curl -s https://api.github.com/users/octocat | jq '.login, .name, .public_repos'
# Pretty print with coloured output (jq does this by default in terminal)
jq -C . data.json | less -R
# ── Python (built-in, no install needed) ──────────────────────────────
echo '{"a":1,"b":[2,3]}' | python3 -m json.tool
# From a file
python3 -m json.tool data.json
# To a file
python3 -m json.tool data.json > pretty.json
# ── Node.js ───────────────────────────────────────────────────────────
echo '{"a":1}' | node -e "
let d='';process.stdin.on('data',c=>d+=c);
process.stdin.on('end',()=>console.log(JSON.stringify(JSON.parse(d),null,2)))
"Pretty Printing JSON in Go
package main
import (
"bytes"
"encoding/json"
"fmt"
)
type User struct {
Name string `json:"name"`
Score []int `json:"scores"`
}
func main() {
// Pretty print a struct
user := User{Name: "Alice", Score: []int{98, 87, 92}}
b, err := json.MarshalIndent(user, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(b))
// Re-format (pretty print) a raw JSON byte slice
raw := []byte(`{"name":"Bob","scores":[70,80]}`)
var buf bytes.Buffer
if err := json.Indent(&buf, raw, "", " "); err != nil {
panic(err)
}
fmt.Println(buf.String())
}Pretty Printing JSON in Java
// ── Jackson ───────────────────────────────────────────────────────────
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
// Pretty print an object
String pretty = mapper.writeValueAsString(myObject);
// Re-format a raw JSON string
Object obj = mapper.readValue(rawJsonString, Object.class);
String formatted = mapper.writeValueAsString(obj);
// ── Gson ──────────────────────────────────────────────────────────────
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String pretty = gson.toJson(myObject);
// Re-format a raw JSON string
JsonElement element = JsonParser.parseString(rawJsonString);
String formatted = gson.toJson(element);Pretty Printing JSON in Rust
// Using serde_json — add to Cargo.toml: serde_json = "1.0"
use serde_json::{json, Value};
fn main() {
let data = json!({
"name": "Alice",
"scores": [98, 87, 92]
});
// Pretty print with to_string_pretty
let pretty = serde_json::to_string_pretty(&data).unwrap();
println!("{}", pretty);
// Re-format a raw JSON string
let raw = r#"{"a":1,"b":[2,3]}"#;
let v: Value = serde_json::from_str(raw).unwrap();
println!("{}", serde_json::to_string_pretty(&v).unwrap());
}Key Facts
- JavaScript:
- JSON.stringify(obj, null, 2) — third arg is indent
- Python:
- json.dumps(data, indent=2) — or python3 -m json.tool from CLI
- Go:
- json.MarshalIndent(v, "", " ") — second arg is prefix, third is indent
- Java (Jackson):
- mapper.enable(SerializationFeature.INDENT_OUTPUT)
- Terminal:
- jq . file.json — fastest, most feature-rich
- curl:
- curl -s URL | jq . — API response debugging
Related Tools
- Format JSON Online — live formatter tool
- JSON Beautifier Online — beautifier-focused guide
- Minify JSON Online — the opposite operation
- JSON Formatter JavaScript — deep-dive on JS JSON APIs
- JSON Diff Tool — compare two JSON documents
- JSON Path Finder — query nested JSON fields