ENRU

How to pretty print JSON

Updated

Pretty printing adds line breaks and indentation. That is all it should do. Many tools also parse the JSON and print it back, and on the way 1.10 turns into 1.1. Below: the command for each language and editor, and what it changes besides whitespace.

Pretty print JSON: commands at a glance

WhereCommandWhat else changes
Python, terminalpython3 -m json.tool data.json1.10 becomes 1.1; accented letters become \u00eb escapes
Python, codejson.dumps(data, indent=2)The same: values are printed back from Python types
jq 1.7+jq . data.jsonDigits stay; string escapes and exponents may be rewritten
JavaScriptJSON.stringify(value, null, 2)Big integers rounded, 1.10 becomes 1.1, integer keys move first
Gojson.Indent(&out, raw, "", " ")Nothing: only whitespace
PowerShellConvertTo-Json -Depth 100Values printed back; without -Depth, deep levels turn into strings
VS Code, IntelliJFormat Document, Reformat CodeNothing: only whitespace
Notepad++, SublimeA plugin: JSON Viewer, JSTool, Pretty JSONDepends on the plugin
OnlineJSON FormatterNothing: only whitespace; keys sorted only on request

Pretty print JSON in Python

import json

with open("data.json", encoding="utf-8") as f:
    data = json.load(f)

print(json.dumps(data, indent=2, ensure_ascii=False))

with open("pretty.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)
    f.write("\n")

indent takes a number of spaces or a string such as "\t". Without ensure_ascii=False, every character outside basic Latin is written as an escape: Zoë becomes Zo\u00eb. Add sort_keys=True for A–Z keys. Python keeps big integers exactly, but floats go through float: 1.10 is printed as 1.1 and 1E3 as 1000.0.

From the terminal, the same module does it without a script:

python3 -m json.tool data.json
python3 -m json.tool --indent 2 data.json pretty.json
python3 -m json.tool --tab --sort-keys --no-ensure-ascii data.json
curl -s https://example.com/api/items | python3 -m json.tool

The default indent is 4 spaces; --indent, --tab and --no-ensure-ascii need Python 3.9 or later. On Windows the command is often py -m json.tool. Never name the same file as input and output: on Python 3.9 the output file is opened first, so the input is empty by the time it is read, and the file is lost.

Pretty print JSON with jq

jq . data.json
jq --indent 4 . data.json
jq --tab . data.json
jq -S . data.json > sorted.json
curl -s https://example.com/api/items | jq .

The . filter prints its input unchanged, indented by 2 spaces; --indent accepts up to 7, -S sorts keys. Since 1.7, jq keeps numbers as written: 1.10 and 12345678901234567890 survive. Older versions convert every number to a double. Even 1.7 rounds as soon as you compute (.n + 0), turns \u00eb into ë, \/ into / and 1E3 into 1E+3.

JavaScript: JSON.stringify with indent

const pretty = JSON.stringify(JSON.parse(text), null, 2);
const withTabs = JSON.stringify(JSON.parse(text), null, '\t');

// Node.js, from stdin:
// node -e 'console.log(JSON.stringify(JSON.parse(require("fs").readFileSync(0, "utf8")), null, 2))' < data.json

Fine for data your own code created. For someone else’s file, know what the round trip through JSON.parse does:

  • Integers above 2^53 − 1 are rounded: 12345678901234567890 comes back as 12345678901234567000. Details in big numbers in JSON.
  • Number notation is lost: 1.10 becomes 1.1, 1e3 becomes 1000.
  • Integer-like keys jump to the front in ascending order: {"b":1,"10":2,"2":3} prints "2", "10", "b". Why: key order in JSON.
  • The indent is capped at 10: a bigger number gives 10 spaces, a longer string is cut to 10 characters.
  • Values JSON can’t hold: a BigInt throws TypeError: Do not know how to serialize a BigInt, undefined and functions disappear, NaN and Infinity become null, dates become strings like "1970-01-01T00:00:00.000Z".

Go: json.Indent and json.MarshalIndent

raw, err := os.ReadFile("data.json")
if err != nil {
	log.Fatal(err)
}
var out bytes.Buffer
if err := json.Indent(&out, raw, "", "  "); err != nil {
	log.Fatal("invalid JSON: ", err)
}
fmt.Println(out.String())

json.Indent copies the input token by token and only adds whitespace, so numbers, escapes and key order stay as written. Broken input returns an error such as invalid character '}' looking for beginning of object key string. json.MarshalIndent is different: it formats a Go value, so a map[string]any comes out with sorted keys, big integers rounded through float64, and <, >, & escaped as \u003c, \u003e, \u0026. Use it for your own structs, json.Indent for files.

PowerShell: ConvertTo-Json -Depth

Get-Content data.json -Raw | ConvertFrom-Json | ConvertTo-Json -Depth 100
Get-Content data.json -Raw | ConvertFrom-Json | ConvertTo-Json -Depth 100 | Set-Content pretty.json -Encoding utf8

-Raw reads the file as one string. -Depth matters: by default ConvertTo-Json goes 2 levels deep and turns anything deeper into a string like @{id=1}; PowerShell 7.1 and later warn about it, Windows PowerShell 5.1 does it silently. The maximum is 100. Values are printed back by PowerShell itself, so notation can change. Windows PowerShell 5.1 indents unevenly and -Encoding utf8 there adds a BOM; PowerShell 7 (pwsh) indents by 2 spaces and writes UTF-8 without one.

Format JSON in VS Code

  1. Open the .json file. For pasted text, create a new file (Ctrl/Cmd+N), paste, then set the language: Ctrl/Cmd+K, then M, type JSON.
  2. Run Format Document: Shift+Alt+F on Windows, Shift+Option+F on macOS, Ctrl+Shift+I on Linux, or from the Command Palette (Ctrl/Cmd+Shift+P).
  3. To format only a part, select it and press Ctrl/Cmd+K, then Ctrl/Cmd+F (Format Selection).
  4. The indent comes from the editor: click Spaces: 4 in the status bar to change it. To format on every save, set "editor.formatOnSave": true.

The built-in JSON formatter changes only whitespace and keeps comments in JSON with Comments files such as settings.json (comments in JSON). If Format Document is missing or asks you to install a formatter, the file isn’t in JSON mode: repeat step 1.

Format JSON in Notepad++, with and without a plugin

With the JSON Viewer plugin

  1. Plugins > Plugins Admin, find JSON Viewer on the Available tab, tick it and press Install. Notepad++ restarts.
  2. Open the file or paste the JSON.
  3. Plugins > JSON Viewer > Format JSON, or Ctrl+Alt+Shift+M.

JSTool works the same way: Plugins > JSTool > JSFormat (Ctrl+Alt+M). Both plugins also show the document as a tree in a side panel.

Without a plugin

Notepad++ has no JSON formatter of its own: Language > J > JSON only colours the text and folds blocks. Don’t reach for a regex that puts a line break after every comma and brace: commas and braces inside strings get broken too. Paste the text into an online formatter and copy it back, or let Python do it through Run > Run… (F5):

python -m json.tool --indent 2 "$(FULL_CURRENT_PATH)" "$(CURRENT_DIRECTORY)\$(NAME_PART).pretty.json"

This writes name.pretty.json next to the original; open it with File > Open. If python isn’t found, use py. Keep the output file different from the input, for the reason in the Python section.

Format JSON in IntelliJ and other JetBrains IDEs

Code > Reformat Code: Ctrl+Alt+L on Windows and Linux, Cmd+Option+L on macOS. Without a selection it formats the whole file. Indent size and wrapping live in Settings > Editor > Code Style > JSON. For a snippet with no file, create a scratch file (Ctrl+Alt+Shift+Insert, or Cmd+Shift+N on macOS), choose JSON, paste and reformat. PyCharm, WebStorm, GoLand and the rest of the family use the same shortcut.

Format JSON in Sublime Text

Sublime Text can’t reformat JSON out of the box. Install the Pretty JSON package: Command Palette (Ctrl/Cmd+Shift+P) > Package Control: Install Package > Pretty JSON. Then run Pretty JSON: Format JSON from the palette. View > Syntax > JSON adds colours and folding.

Pretty print JSON online

Paste the text into the JSON Formatter, drop a file or press Ctrl/Cmd+O (up to 1 MiB), pick 2 spaces, 4 spaces or Tab and press Ctrl/Cmd+Enter. Only whitespace changes: 1.10, 12345678901234567890 and the key order come back as written; sorting keys is a separate switch you turn on. Broken JSON gets its first error with a line and a column instead of a guess; to only check, use the Validator. The text goes to our API over HTTPS, is processed in memory and isn’t stored (Security & data). The opposite, one line without whitespace, is the Minifier.

Pretty print JSON FAQ

Does pretty printing change the data?

It shouldn’t, but many tools parse and print back, so values pass through the language’s types. Whitespace only: Go’s json.Indent, VS Code, IntelliJ and our formatter. Parse and print back: JSON.stringify, json.dumps, ConvertTo-Json. jq 1.7 sits in between: digits stay, escapes may be rewritten.

2 spaces, 4 spaces or tabs?

JSON doesn’t care: whitespace between tokens has no meaning (RFC 8259, section 2). jq and most JavaScript projects use 2 spaces, Python’s json.tool defaults to 4. Pick one per project and let the formatter enforce it.

How do I pretty print a curl response?

Pipe it: curl -s URL | jq . or curl -s URL | python3 -m json.tool. If you get a parse error about <, the server sent an HTML page, not JSON: see Unexpected token.

How do I pretty print a JSON Lines file?

jq . file.jsonl prints every record indented; python3 -m json.tool --json-lines file.jsonl does the same. The result is no longer JSON Lines: see JSON Lines.