Pretty Print JSON in JavaScript: Browser and Node.js Examples

Pretty printing JSON means adding line breaks and indentation so humans can read it. In JavaScript, the standard way is JSON.stringify(value, null, 2).

Pretty print a JavaScript object

If you already have a JavaScript object, stringify it with a spacing argument. Two spaces is the safest default for docs, config examples, and debug output.

const data = {
  user: {
    id: 42,
    name: 'Alice'
  },
  roles: ['admin', 'editor']
}

const pretty = JSON.stringify(data, null, 2)
console.log(pretty)

Pretty print a JSON string

If the input is already a JSON string, parse it first, then stringify the parsed value.

const raw = '{"user":{"id":42,"name":"Alice"},"roles":["admin","editor"]}'
const pretty = JSON.stringify(JSON.parse(raw), null, 2)

console.log(pretty)

// {
//   "user": {
//     "id": 42,
//     "name": "Alice"
//   },
//   "roles": [
//     "admin",
//     "editor"
//   ]
// }

Handle invalid JSON safely

Pretty printing a string requires parsing, and parsing can throw. Wrap untrusted input intry/catch.

function prettyPrintJson(raw) {
  try {
    return {
      ok: true,
      value: JSON.stringify(JSON.parse(raw), null, 2)
    }
  } catch (error) {
    return {
      ok: false,
      error: error instanceof Error ? error.message : 'Invalid JSON'
    }
  }
}

Choose 2 spaces, 4 spaces, or tabs

The third argument accepts a number or a string. Numbers are clamped to 10 spaces. Strings are used as the indentation unit.

JSON.stringify(data, null, 2)   // 2 spaces
JSON.stringify(data, null, 4)   // 4 spaces
JSON.stringify(data, null, '	') // tabs

For shared examples, use 2 spaces unless your project has a strong convention.

Pretty print JSON in the browser

A small browser formatter can read a textarea, parse the JSON, and write formatted output.

const input = document.querySelector('#json-input')
const output = document.querySelector('#json-output')

try {
  output.textContent = JSON.stringify(JSON.parse(input.value), null, 2)
} catch (error) {
  output.textContent = 'Invalid JSON'
}

Pretty print JSON in Node.js

For scripts, parse stdin or file content, then output formatted JSON.

import { readFileSync } from 'node:fs'

const raw = readFileSync('data.json', 'utf8')
const pretty = JSON.stringify(JSON.parse(raw), null, 2)

console.log(pretty)

Common mistakes

  • Calling JSON.stringify(raw, null, 2) on a JSON string instead of parsing it first.
  • Expecting pretty printing to fix invalid JSON syntax.
  • Forgetting that functions, undefined, and symbols do not appear in JSON output.
  • Pretty printing large files in the UI thread without considering browser performance.

Pretty print JSON instantly

Use Jsonic's JSON Formatter when you want readable output, validation errors, minification, file upload, and copy/download actions in one place.

Open JSON Formatter