Format & Pretty-Print JSON in JavaScript, Python, Go & Rust
Formatting un-indented JSON payloads into readable, structured data is a daily task in debugging, logging, and API development. Here is the definitive cheat sheet for pretty-printing JSON across the most popular backend languages, handling edge cases like circular references and streaming large files.
1. JavaScript & Node.js: JSON.stringify(obj, replacer, space)
The third parameter of JSON.stringify controls indentation spacing (typically 2 spaces). To filter or transform keys during formatting, pass a replacer function as the second parameter.
const rawData = { service: "auth-worker", port: 8080, tags: ["prod", "us-east"] };
// 2-space indentation pretty-print
const formatted = JSON.stringify(rawData, null, 2);
console.log(formatted);
Handling Circular References in JavaScript
Objects that reference themselves directly or indirectly throw TypeError: Converting circular structure to JSON. Use a custom WeakSet replacer to safely prune circular branches:
function getSafeCircularReplacer() {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) return "[Circular Ref]";
seen.add(value);
}
return value;
};
}
const safeJson = JSON.stringify(circularObject, getSafeCircularReplacer(), 2);
2. Python: json.dumps(obj, indent=2, sort_keys=True)
Python's built-in json module provides indent for indentation and sort_keys=True for deterministic output ordering (ideal for testing and snapshot diffing).
import json
payload = {"name": "Athena", "cluster": "prod-01", "replicas": 5}
# Pretty-print with 2 spaces and sorted keys
formatted_json = json.dumps(payload, indent=2, sort_keys=True)
print(formatted_json)
3. Go: json.MarshalIndent(v, "", " ")
In Go, pretty-printing is handled via json.MarshalIndent. The second argument is a line prefix (usually empty "") and the third is the indentation token (" ").
package main
import (
"encoding/json"
"fmt"
)
type Config struct {
Host string `json:"host"`
Port int `json:"port"`
}
func main() {
cfg := Config{Host: "localhost", Port: 9000}
bytes, _ := json.MarshalIndent(cfg, "", " ")
fmt.Println(string(bytes))
}
4. Terminal CLI: Instant Formatting with jq
When working on the command line or parsing curl responses, pipe standard output directly into jq:
# Pretty print a local JSON file
cat data.json | jq .
# Pretty print live API response with curl
curl -s https://api.github.com/zen | jq .