Back to NiceJSON
NiceJSON Blog/ How to Format and Pretty Print JSON Online and in Code

How to Format and Pretty Print JSON Online and in Code

Step-by-step ways to format, beautify, and pretty print JSON: with an online formatter, JavaScript, Python, and the command line.

2 min read
  • json
  • formatter
  • how-to

Why format JSON?

APIs and minifiers usually return JSON on a single line. That is efficient for machines but nearly impossible for people to scan. Formatting (also called pretty printing or beautifying) adds line breaks and indentation so the structure becomes obvious.

Compare:

{"id":7,"name":"Ada","roles":["admin","dev"],"profile":{"city":"London","active":true}}

with the formatted version:

{
  "id": 7,
  "name": "Ada",
  "roles": ["admin", "dev"],
  "profile": {
    "city": "London",
    "active": true
  }
}

The data is identical. Only whitespace changed.

Method 1: an online formatter

The fastest option needs no setup:

  1. Open NiceJSON.
  2. Paste your JSON into the editor.
  3. Click Format.

NiceJSON formats in your browser, so your data is not uploaded to a server for the basic formatting workflow. Invalid JSON is flagged with the error position so you can fix it first.

Method 2: JavaScript

JSON.stringify accepts a third argument that controls indentation.

const data = { id: 7, name: "Ada", roles: ["admin", "dev"] };
 
console.log(JSON.stringify(data, null, 2)); // 2 spaces
console.log(JSON.stringify(data, null, "\t")); // tabs

Method 3: Python

import json
 
data = {"id": 7, "name": "Ada", "roles": ["admin", "dev"]}
print(json.dumps(data, indent=2, sort_keys=True))

Method 4: the command line

With jq:

echo '{"id":7,"name":"Ada"}' | jq .

With Python only:

echo '{"id":7,"name":"Ada"}' | python3 -m json.tool

Choosing an indent size

StyleBest for
2 spacesWeb projects, config files, most style guides
4 spacesPython and Java ecosystems
TabsTeams that prefer per-editor tab width

Pick one and stay consistent across a repository so diffs stay clean.

Smarter layouts

Plain indentation puts every array element on its own line, which makes arrays of numbers very tall. NiceJSON uses a FracturedJson-style layout that keeps short arrays and objects compact on one line while expanding only the complex parts. The result is much shorter to read. See our article on FracturedJson vs standard formatting for details.

Tips

  • Format before you diff or commit so changes are easy to review.
  • Format after you minify for transport, when you need to debug a payload.
  • Validate first: a formatter cannot fix invalid JSON.