JSON Formatter Online

A JSON Formatter (also called a JSON beautifier or JSON pretty-printer) is a free online tool that beautifies, validates, and structures JSON data. It catches every JSON syntax error and applies JSON validation rules so your data is clean before it reaches production.

starstarstarstarstar
4.8· 2,341 ratings
1234567891011121314151617181920
1234567891011121314151617181920
format_indent_increase

Indentation

format_quote

Formatting Rules

security

Privacy & Speed

Local-only processing. Your data never leaves your browser. Optimized for large files up to 50MB.

boltSECURE END-TO-END
shieldRuns entirely in your browser
cloud_offNo data stored or uploaded
volunteer_activismFree forever

What is JSON Formatting?

JSON formatting (also called JSON beautifying or pretty-printing) is the process of converting compact, hard-to-read JSON text into a structured, indented layout that developers can scan instantly. Raw JSON returned by APIs or stored in databases is typically minified — all on one line — to save space. A JSON formatter acts as a JSON linter: it parses the input, applies JSON validation rules (RFC 8259), and re-serialises it with consistent indentation so objects, arrays, keys, and values become immediately visible. If the input contains a JSON syntax error, use our JSON validator and syntax checker to pinpoint the exact line and character position of the problem.

Features of OpenFormatter JSON Formatter

  • lock100% client-side — your JSON never leaves the browser. No server upload, no data logging, no privacy risk.
  • format_align_leftInstant pretty-print with 2-space, 4-space, or tab indentation — choose the style that matches your codebase.
  • verifiedBuilt-in validator — syntax errors are caught and reported the moment you click Beautify.
  • compressOne-click minification strips all whitespace for compact production payloads.
  • downloadDownload formatted output as a .json file or copy it straight to your clipboard.

When to Use JSON Formatter

api

API Debugging

Paste a raw API response and instantly see the full data structure, nested objects, and missing fields.

settings

Config Files

Clean up package.json, tsconfig, or .eslintrc files with consistent indentation before committing.

verified

Validation

Catch trailing commas, unquoted keys, and other syntax errors before they break your build or API call.

JSON Formatter Example

Paste minified JSON on the left — the formatter outputs clean, indented JSON on the right.

remove_circle

Before Formatting

{"name":"John","age":30,"address":{"city":"New York","zip":"10001"}}
check_circle

After Formatting

{
  "name": "John",
  "age": 30,
  "address": {
    "city": "New York",
    "zip": "10001"
  }
}

FAQs

Is it safe to paste sensitive JSON here?expand_more
Yes. All processing happens in your browser using JavaScript. Nothing is sent to any server.
What is the difference between a JSON formatter and a JSON validator?expand_more
A formatter makes JSON readable. A validator checks whether JSON is syntactically correct. This tool does both — it validates during formatting and reports errors if the input is invalid.
Can I format large JSON files?expand_more
Yes. Because processing is client-side, performance depends on your browser and device. Files up to several MB format instantly on modern hardware.
What indentation should I use — 2 spaces or 4?expand_more
2 spaces is standard in JavaScript, JSON, and most web projects. 4 spaces is common in Python and Java. Either is valid; pick what matches your team style guide.
Does formatting change my data?expand_more
No. Formatting only adds whitespace. The data values, keys, and structure are identical before and after.
Overview

What is a JSON Formatter?

A JSON formatter (also called a JSON beautifier, JSON linter, or JSON pretty-printer) is a tool that takes raw or minified JSON text and reformats it with consistent indentation, line breaks, and spacing so it becomes human-readable. You can format JSON using our tool above — just paste and click Beautify.

JSON (JavaScript Object Notation) is the standard data format for APIs, configuration files, and data storage. While machines handle compact JSON efficiently, developers need formatted JSON to read, debug, and review data structures quickly. Need to check correctness first? Use our free JSON validator to detect any JSON syntax errors before formatting.

OpenFormatter's JSON formatter runs 100% in your browser — no server upload, no data exposure, instant results even for large files. It applies standard JSON validation rules on every parse, so invalid input is caught immediately rather than silently corrupting your output.

format_align_left

Pretty-print

Adds indentation and line breaks for readability

verified

Validate

Catches syntax errors before they reach production

compress

Minify

Strip whitespace for compact transport payloads

download

Export

Download formatted JSON as a .json file

Use Cases

Why Use an Online JSON Formatter

From debugging API responses to reviewing config files, a JSON formatter is one of the most-reached-for tools in a developer's daily workflow. You can format JSON using our tool above, then copy or download the result. Need the reverse? Use our free JSON minifier tool to compress formatted JSON back into a single line. You can also browse JSON examples by use case to see common patterns before writing your own.

api

API Debugging

REST and GraphQL APIs return minified JSON payloads. Paste the raw response into the formatter to instantly see the full data structure, spot missing fields, and verify that your API contract matches expectations.

RESTGraphQLWebhooks
article

Log Analysis

Modern applications emit structured JSON logs — from Node.js servers, Lambda functions, and cloud platforms. Formatting these one-liners makes it practical to trace errors, correlate request IDs, and understand event sequences.

CloudWatchDatadogSplunk
settings

Config Files

package.json, tsconfig.json, .eslintrc, and other config files need to stay readable as projects grow. Run them through the formatter to fix inconsistent indentation and catch syntax errors before they break your build.

package.jsontsconfig.eslintrc
Under the Hood

How to Format JSON Online

Formatting happens in three stages — parse, transform, serialize.

01

Parsing

The input string is parsed into an in-memory object tree using the browser's native JSON.parse(). This step validates the syntax and catches errors like missing quotes, trailing commas, or mismatched brackets.

JSON.parse('{"name":"Alice","age":30}')
02

Optional Transforms

Optional rules are applied to the parsed object — removing null values, sorting keys alphabetically, or flattening nested structures — before serialization.

JSON.parse(JSON.stringify(obj, (k,v) => v ?? undefined))
03

Serialization

The object is serialized back to a string using JSON.stringify() with an indentation argument (2 or 4 spaces), producing the formatted output instantly.

JSON.stringify(parsed, null, 2)
Comparison

JSON Formatter vs Validator vs Viewer

These three tools are related but serve distinct purposes. Here's when to reach for the validate JSON online tool or the free JSON Viewer tool instead of this formatter:

ToolPrimary PurposeOutputBest For
JSON FormatterThis toolBeautify / pretty-printIndented, readable JSON stringMaking minified JSON human-readable
JSON ValidatorCheck syntax correctnessPass / fail with error locationVerifying JSON before deploying or sending to an API
JSON ViewerBrowse structure interactivelyCollapsible tree UIExploring deeply nested or large JSON structures
Comparison

JSON Beautifier vs Minifier

Both tools transform JSON — but in opposite directions. Knowing when to use each one will save you debugging time and reduce API overhead.

format_align_left

JSON Beautifier

Also called: formatter, pretty-printer

  • check_circleAdds indentation, line breaks, and spacing
  • check_circleMakes nested structures immediately readable
  • check_circleIncreases file size (whitespace overhead)
  • check_circleUsed during development, debugging, and code review
  • check_circleInput: {"name":"Alice","age":30}

{ "name": "Alice", "age": 30 }

compress

JSON Minifier

Also called: compressor, JSON minify

  • check_circleStrips all whitespace, line breaks, and indentation
  • check_circleProduces the smallest possible JSON string
  • check_circleReduces payload size for faster API responses
  • check_circleUsed before deploying to production or sending over the wire
  • check_circleOutput: {"name":"Alice","age":30}

{"name":"Alice","age":30}

Rule of thumb: beautify when you're reading JSON, minify when you're sending it. Use the online JSON minifier if you need to compress output after formatting.

Troubleshooting

Common JSON Errors

These are the most frequent causes of invalid JSON. Each invalid JSON example below includes the exact error and the corrected version. Paste your broken JSON into the formatter above — it will highlight the error location. For a dedicated error report with line numbers and a full guide, visit our JSON errors guide or try the JSON syntax checker. Note: these tools check syntax validity only — for JSON schema validation (type-level checking against a schema definition), you need a dedicated JSON Schema validator.

error

Trailing comma

JSON does not allow a comma after the last element in an object or array. This is valid JavaScript but invalid JSON.

Invalid

{"name": "Alice", "age": 30,}

Valid

{"name": "Alice", "age": 30}
error

Unquoted keys

All object keys must be enclosed in double quotes. Single quotes and unquoted keys are not valid JSON.

Invalid

{name: "Alice", age: 30}

Valid

{"name": "Alice", "age": 30}
error

Single quotes

String values must use double quotes. Single-quoted strings are JavaScript syntax, not valid JSON.

Invalid

{"name": 'Alice'}

Valid

{"name": "Alice"}
error

Undefined / NaN / Infinity

JSON only supports null for absence of value. JavaScript-specific values like undefined, NaN, and Infinity are not valid JSON.

Invalid

{"value": undefined, "score": NaN}

Valid

{"value": null, "score": null}
error

Comments

JSON does not support comments. Use JSON5 or JSONC if you need comments in config files.

Invalid

{"name": "Alice" // user name}

Valid

{"name": "Alice"}
Examples

JSON Formatting Examples

Simple Object

Minified input

{"user":{"id":1,"name":"Alice","role":"admin","active":true}}

Formatted output

{
  "user": {
    "id": 1,
    "name": "Alice",
    "role": "admin",
    "active": true
  }
}

Array of Objects

Minified input

[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"},{"id":3,"name":"Charlie"}]

Formatted output

[
  { "id": 1, "name": "Alice" },
  { "id": 2, "name": "Bob" },
  { "id": 3, "name": "Charlie" }
]

API Response

Minified input

{"status":"success","data":{"token":"eyJhbGc...","expires_in":3600},"meta":{"request_id":"abc123","timestamp":1704067200}}

Formatted output

{
  "status": "success",
  "data": {
    "token": "eyJhbGc...",
    "expires_in": 3600
  },
  "meta": {
    "request_id": "abc123",
    "timestamp": 1704067200
  }
}
Guide

API Debugging Guide

When an API request fails or returns unexpected data, a JSON formatter is the fastest way to understand what went wrong. Here's a repeatable debugging workflow:

1

Capture the raw response

Copy the raw response body from your browser's DevTools (Network tab → select request → Response tab), Postman, or curl output.

curl -s https://api.example.com/users | pbcopy
2

Paste and format

Paste into the formatter above and click Beautify. If it errors, the JSON itself is malformed — check for encoding issues or truncated responses.

3

Inspect structure

Look for unexpected null values, empty arrays, missing fields, or wrong data types. These are often the root cause of client-side errors.

4

Compare against schema

Copy the expected shape from your API docs or TypeScript types and compare side-by-side with the actual response. Field name mismatches (camelCase vs snake_case) are common.

5

Validate before sending

If you're crafting a request body, format and validate it before sending to avoid 400 Bad Request errors caused by malformed JSON.

Use the JSON Validator tab for strict schema checking
lightbulb

Pro tip: For large API responses (>10MB), use the Upload button in the toolbar to load your JSON file directly — it's faster than pasting and avoids browser clipboard limits.

FAQ

Frequently Asked Questions

What is a JSON formatter?expand_more
A JSON formatter is a tool that takes compact or minified JSON text and reformats it with indentation and line breaks, making it easy for humans to read and understand the data structure.
Is this JSON formatter free?expand_more
Yes, completely free with no usage limits. OpenFormatter's formatting tools are free for everyone and always will be.
Is my data safe? Does it get uploaded to a server?expand_more
No data is ever uploaded. All formatting happens entirely in your browser using JavaScript. Your JSON never leaves your device — not even in encrypted form. You can verify this by opening your browser's Network inspector while formatting.
What's the difference between a JSON formatter and a JSON beautifier?expand_more
They are the same thing. "Formatter", "beautifier", and "pretty-printer" all refer to the same operation: adding indentation and whitespace to make JSON human-readable. The terms are used interchangeably.
Can I format invalid JSON?expand_more
No — to format JSON, it must first be valid. If your JSON contains syntax errors (trailing commas, unquoted keys, single quotes), the formatter will show an error. Fix the syntax first, then format. The error message will point to the location of the problem.
What indentation should I use — 2 spaces or 4 spaces?expand_more
2-space indentation is the most common convention in JavaScript, TypeScript, and modern web APIs. 4-space indentation is common in Python and Java ecosystems. Either is valid JSON — choose based on your team's style guide.
How do I format JSON in JavaScript?expand_more
Use JSON.stringify() with an indentation argument: JSON.stringify(yourObject, null, 2). The third argument sets the number of spaces. To parse a JSON string first: JSON.stringify(JSON.parse(jsonString), null, 2).
How do I format JSON in Python?expand_more
Use json.dumps() with indent parameter: import json; print(json.dumps(your_dict, indent=2)). To read and format a JSON file: json.dumps(json.load(open("file.json")), indent=2).
Can this format large JSON files?expand_more
Yes. The formatter handles files up to ~50MB efficiently since all processing happens locally in your browser. For very large files, use the Upload button in the toolbar instead of pasting.
What's the difference between JSON and JSON5?expand_more
JSON5 is a superset of JSON that allows comments, trailing commas, single-quoted strings, and unquoted keys — making it more comfortable for humans to write. JSON5 is used in some config files (like Babel or ESLint). Standard JSON parsers cannot parse JSON5 — use the JSON5 Formatter for those files.
Why does my formatted JSON look different from the original?expand_more
Formatting reserializes the parsed object. This means key order may change (objects don't have guaranteed key order in JSON), and insignificant whitespace differences disappear. The data itself is identical — only the presentation changes.
Terminal

Format JSON from the Terminal

Need to format JSON without leaving your terminal? Here are the fastest one-liners for every platform — no extra tools required for Python and Node.js. For piping API responses, jq is the standard choice.

PythonBuilt-in

Format a file

python3 -m json.tool data.json

Pipe from stdin

echo '{"name":"Alice"}' | python3 -m json.tool

Write formatted to new file

python3 -m json.tool data.json > pretty.json
Node.jsBuilt-in

Format a file

node -e "const fs=require('fs');console.log(JSON.stringify(JSON.parse(fs.readFileSync('data.json','utf8')),null,2))"

One-liner for a JSON string

node -e "process.stdout.write(JSON.stringify(JSON.parse(require('fs').readFileSync('/dev/stdin','utf8')),null,2))" < data.json
jqInstall required

Format a file

jq . data.json

Pipe curl API response

curl -s https://api.example.com/users | jq .

Extract a field

curl -s https://api.example.com/users | jq '.[0].name'

Install on macOS

brew install jq
cURL + Pretty PrintCommon pattern

curl + python

curl -s https://api.example.com/data | python3 -m json.tool

curl + jq (recommended)

curl -s https://api.example.com/data | jq .

curl with headers

curl -s -H 'Authorization: Bearer TOKEN' https://api.example.com/me | jq .
Code Reference

How to Format JSON in Your Language

Every major language has a built-in JSON library. Here are the exact functions to pretty-print JSON with consistent indentation — no third-party package needed.

JavaScript / TypeScript
// Format a JSON string
const formatted = JSON.stringify(JSON.parse(raw), null, 2);

// Format an existing object
const formatted = JSON.stringify(myObject, null, 2);

// Write formatted JSON to a file (Node.js)
const fs = require('fs');
fs.writeFileSync('out.json', JSON.stringify(data, null, 2));
Python
import json

# Format a JSON string
formatted = json.dumps(json.loads(raw_str), indent=2)

# Format a Python dict
formatted = json.dumps(my_dict, indent=2)

# Read, format, and write a JSON file
with open('data.json') as f:
    data = json.load(f)
print(json.dumps(data, indent=2))
Go
import (
    "encoding/json"
    "bytes"
)

// Indent a JSON []byte
var out bytes.Buffer
json.Indent(&out, rawJSON, "", "  ")
fmt.Println(out.String())

// Marshal with indentation
b, _ := json.MarshalIndent(myStruct, "", "  ")
Java
// Using Jackson
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String formatted = mapper.writeValueAsString(myObject);

// Parse and re-format a JSON string
Object obj = mapper.readValue(rawJson, Object.class);
String pretty = mapper.writerWithDefaultPrettyPrinter()
                       .writeValueAsString(obj);
PHP
// Format a JSON string
$formatted = json_encode(
    json_decode($rawJson),
    JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE
);

// Format and save to file
file_put_contents('out.json', json_encode(
    json_decode(file_get_contents('data.json')),
    JSON_PRETTY_PRINT
));
Rust
use serde_json::Value;

// Parse then pretty-print
let v: Value = serde_json::from_str(&raw_json)?;
let pretty = serde_json::to_string_pretty(&v)?;

// Pretty-print a struct
#[derive(Serialize)]
struct User { name: String }
let pretty = serde_json::to_string_pretty(&user)?;
Reference

JSON Syntax Cheat Sheet

A complete reference to valid JSON syntax — bookmark this when you need to verify what's allowed and what isn't. JSON is defined by RFC 8259.

Valid JSON Value Types

TypeExample
String"Hello, world!"
Number42 / 3.14 / -7 / 1.5e3
Booleantrue / false
Nullnull
Array[1, "two", true, null]
Object{"key": "value"}

Key Rules

check_circleKeys must be double-quoted strings
check_circleString values use double quotes only
check_circleNumbers may be integer, decimal, or scientific notation
check_circleArrays and objects can be nested arbitrarily
cancelNo trailing commas after last item
cancelNo single-quoted strings
cancelNo comments (use JSON5 or JSONC for that)
cancelNo undefined, NaN, or Infinity values
cancelNo unquoted or numeric keys
cancelNo JavaScript functions or expressions

Invalid JSON

{
  name: "Alice",          // key not quoted
  'role': 'admin',        // single quotes
  "score": NaN,           // NaN not allowed
  "tags": ["a", "b",],   // trailing comma
  // this is a comment   // no comments in JSON
}

Valid JSON

{
  "name": "Alice",
  "role": "admin",
  "score": null,
  "tags": ["a", "b"],
  "active": true
}
Comparison

JSON vs XML, YAML, CSV — Which Should You Use?

JSON is the dominant format for APIs and config files, but it's not always the right choice. Here's how it compares against the other formats you'll encounter in real projects.

FormatBest ForStrengthsWeaknesses
JSONThis toolREST APIs, config files, NoSQL databasesNative to JavaScript, compact, human-readable, universal parser supportNo comments, no schema enforcement, verbose for tabular data
XMLEnterprise systems, SOAP APIs, document formats (SVG, RSS)Attributes + elements, XSLT transformations, mature tooling, namespace supportVerbose, harder to parse, slower, poor JavaScript ergonomics
YAMLConfig files (Docker, GitHub Actions, Kubernetes), human-authored dataComments allowed, minimal syntax, very human-readableWhitespace-sensitive (indent errors silently break files), slow parsers, complex spec
CSVTabular data, spreadsheets, data pipelines, analytics exportsExtremely compact, Excel/Google Sheets compatible, fast to parseFlat structure only (no nesting), no types, no standard for special chars
Protocol BuffersHigh-performance internal APIs, microservices (gRPC)3–10× smaller than JSON, typed, faster serializationBinary (not human-readable), requires schema file, limited browser support

Use JSON when…

  • check_circleBuilding a REST or GraphQL API
  • check_circleStoring data in MongoDB or PostgreSQL JSONB
  • check_circleWriting config files for JS/TS tooling
  • check_circleExchanging data between any two modern services

Use YAML when…

  • check_circleWriting CI/CD pipeline configs (GitHub Actions, GitLab)
  • check_circleAuthoring Kubernetes or Docker Compose files
  • check_circleYou need human-readable configs with comments

Use CSV when…

  • check_circleExporting reports or analytics data
  • check_circleSharing flat tabular data with non-developers
  • check_circleImporting data into spreadsheets or databases in bulk
Performance

Handling Large JSON Files

This formatter handles files up to ~50MB entirely in your browser. For larger files, different strategies apply depending on the source and target. Here's a decision framework used by data engineers and backend developers.

File SizeBest ApproachTool / Command
< 5 MBBrowser-based formatter (this tool)Paste or upload — formats instantly
5–50 MBBrowser upload (recommended)Use the Upload button; avoids clipboard limits
50–500 MBTerminal with jq or pythonjq . large.json > pretty.json
500 MB+Streaming parser or chunkingjq -c . large.json (compact + stream)
Any size (API)Request paginated responsesAdd ?page=1&limit=100 to API calls

Strategies for Very Large JSON

splitscreen

Use NDJSON (Newline-Delimited JSON) for streaming

Instead of one giant JSON array, emit one JSON object per line. Each line is independently parseable. This is the standard format for log ingestion (Datadog, Elasticsearch, BigQuery streaming inserts) and avoids loading the entire file into memory.

{"id":1,"event":"click"}
{"id":2,"event":"scroll"}
{"id":3,"event":"purchase"}
compress

Compress JSON payloads with gzip

JSON compresses extremely well with gzip because of repetitive key names. A typical API response compresses 5–10×. Enable gzip on your server and send Accept-Encoding: gzip from clients. JSON over gzip is usually smaller than equivalent Protocol Buffers without compression.

# Node.js: compress JSON response
res.setHeader("Content-Encoding", "gzip");
res.end(zlib.gzipSync(JSON.stringify(data)));
pageview

Paginate API responses — never return unbounded arrays

Any API endpoint that returns an array should support pagination. The de facto standard is cursor-based pagination (safer than offset for large datasets) using next_cursor fields. This keeps each JSON response small and fast.

{
  "data": [...],
  "meta": {
    "next_cursor": "eyJpZCI6MTAwfQ==",
    "has_more": true
  }
}
schema

Use JSON Schema to validate structure before processing

Before parsing a large JSON file, validate its structure against a JSON Schema. This catches malformed data early without reading every record — critical for data pipelines that process millions of rows. Tools: Ajv (JavaScript), jsonschema (Python), everit-org/json-schema (Java).

const Ajv = require("ajv");
const ajv = new Ajv();
const valid = ajv.validate(schema, data);
if (!valid) console.log(ajv.errors);
JSON Formatter Online – Free JSON Beautifier & Validator