Guides / How to Format and Validate JSON

How to Format and Validate JSON

4 min read · JSON

Why formatting matters

Raw JSON from an API or a database is often minified — all whitespace removed to reduce file size. While this is efficient for machines, it is nearly impossible for humans to read. Formatting (also called "pretty-printing") adds indentation and line breaks to make the structure visible and easy to navigate.

Validation ensures your JSON is syntactically correct before you use it in code. A single misplaced comma or missing quote will cause a parse error at runtime, often with a cryptic error message.

Minified vs formatted JSON

The same data, minified:

{"user":{"id":1,"name":"Ana","roles":["admin","editor"]}}

And formatted with 2-space indentation:

{
  "user": {
    "id": 1,
    "name": "Ana",
    "roles": [
      "admin",
      "editor"
    ]
  }
}

The most common JSON errors

1. Trailing comma

{ "name": "Ana", "age": 28, }  // ❌ comma after last item
{ "name": "Ana", "age": 28 }   // ✅

2. Single quotes instead of double quotes

{ 'name': 'Ana' }  // ❌ single quotes not allowed
{ "name": "Ana" }  // ✅

3. Unquoted keys

{ name: "Ana" }    // ❌ keys must be quoted
{ "name": "Ana" }  // ✅

4. Comments

{ "name": "Ana" // user name }  // ❌ comments not allowed
{ "name": "Ana" }               // ✅

5. Missing commas between items

{ "a": 1 "b": 2 }   // ❌ missing comma
{ "a": 1, "b": 2 }  // ✅

How to read JSON error messages

When JSON fails to parse, the error message usually includes a line and column number. For example: SyntaxError: Unexpected token at line 4, column 12.

Go to line 4, column 12 in your JSON and look for the issue. Common things to check at the error location: a missing comma on the line above, an unclosed string, or an unquoted key.

Our JSON Validator highlights the exact error location in the file, making it much faster to find and fix issues.

Indentation: 2 spaces, 4 spaces, or tabs?

This is mostly a style preference. The most common conventions:

  • 2 spaces — most popular in JavaScript/Node.js projects
  • 4 spaces — common in Python and Java projects
  • Tabs — some teams prefer tabs for accessibility reasons

For JSON that will be stored or transmitted, use minified (no indentation) to reduce file size. For config files or human-readable files, use 2 or 4 spaces.

Formatting JSON in code

In JavaScript/TypeScript:

// Parse a JSON string
const data = JSON.parse('{"name":"Ana"}');

// Format (stringify) with 2-space indentation
const formatted = JSON.stringify(data, null, 2);

// Minify
const minified = JSON.stringify(data);

In Python:

import json

data = json.loads('{"name": "Ana"}')

# Format with 2-space indent
formatted = json.dumps(data, indent=2)

# Minify
minified = json.dumps(data, separators=(',', ':'))

Format your JSON now

Paste any JSON and get it formatted or validated instantly — right in your browser.