JSON Formatter & Validator

Format, validate, and minify JSON instantly — with syntax highlighting and exact error location.

Indent:
Input JSON 0 chars
Formatted output
Status:
Keys:
Depth:
Size:
Advertisement Banner (728x90)

JSON Formatter — Free Online JSON Beautifier, Validator & Minifier

Format messy JSON with syntax highlighting, validate and find errors with exact line numbers, minify for production, and explore structure with stats. Free, runs in your browser, no data sent to any server.

By Imtiaz Ali  |  OurToolkit  |  Updated June 2026

What Is JSON? — A Developer's Practical Overview

JSON — JavaScript Object Notation — is a text-based data interchange format specified in ECMA-404 and RFC 8259. It was popularised by Douglas Crockford in the early 2000s as a simpler alternative to XML for transmitting data between web clients and servers. Despite its name containing "JavaScript," JSON is completely language-independent and is natively supported in every major programming language including Python, Java, PHP, Ruby, Go, Rust, Swift, Kotlin, and C#. When JSON payloads contain URLs or special characters, use our URL encoder/decoder to safely process them.

JSON has become the de facto standard for REST API responses, webhook payloads, configuration files, and NoSQL database documents. It powers the data layer of virtually every modern web and mobile application. When a weather app fetches the current temperature, when your browser loads your Twitter timeline, when an e-commerce site processes an order — JSON is almost certainly the format carrying that data. API authentication often involves Base64-encoded credentials in JSON payloads.

The format's dominance comes from three qualities: it is genuinely human-readable when formatted, it maps naturally to the data structures found in virtually every programming language (objects/dictionaries and arrays/lists), and it is significantly more compact than XML for equivalent data structures.

JSON Syntax — Complete Rules Reference

JSON has exactly six data types and a small set of syntax rules. Unlike programming languages, it has no flexibility or forgiveness — a single character out of place makes the entire document invalid. Understanding these rules is the difference between wasting time debugging and fixing errors in seconds.

The six JSON data types

TypeSyntaxValid exampleCommon mistake
StringDouble-quoted text"Hello World"Using single quotes: 'Hello'
NumberInteger or decimal42 or 3.14Using NaN or Infinity
BooleanLowercase onlytrue or falseCapitalised: True
NullLowercase onlynullCapitalised: Null or NULL
ObjectKey-value pairs in {}{"key": "value"}Unquoted keys: {key: "value"}
ArrayOrdered list in [][1, 2, 3]Trailing comma: [1, 2, 3,]

JSON object syntax rules

A JSON object is a collection of key-value pairs enclosed in curly braces. Every key must be a string enclosed in double quotes (use our URL encoder to properly encode keys containing special characters). Keys and values are separated by a colon. Pairs are separated by commas. The final pair must not have a trailing comma. An empty object is valid: {}.

{ "name": "Alice", "age": 28, "active": true, "address": null }

JSON array syntax rules

A JSON array is an ordered list of values enclosed in square brackets. Values can be of any JSON type and can be mixed types within the same array. Values are separated by commas. The final value must not have a trailing comma. An empty array is valid: []. Arrays can be nested inside objects and objects can be nested inside arrays to any depth.

[ "apple", 42, true, null, {"key": "value"} ]

The Most Common JSON Errors — and Exactly How to Fix Them

Every developer who works with JSON regularly has encountered the same set of errors repeatedly. The JSON validator in this tool detects all of these and shows the exact position where the error occurs. When debugging JSON errors from URL-encoded parameters or Base64-encoded payloads, decode them first using our specialized tools, then validate with this formatter.

Error typeInvalid exampleFixed exampleWhy it fails
Single quotes {'name': 'Alice'} {"name": "Alice"} JSON requires double quotes for all strings and keys. Single quotes are only valid in JavaScript, not JSON.
Trailing comma {"a": 1, "b": 2,} {"a": 1, "b": 2} JSON does not allow a comma after the last element in an object or array. JavaScript allows this; JSON does not.
Comments {"a": 1 // comment} {"a": 1} JSON does not support comments of any kind. Remove all // and /* */ comments before parsing.
Unquoted key {name: "Alice"} {"name": "Alice"} All JSON keys must be strings enclosed in double quotes. Unquoted keys are JavaScript object syntax, not JSON.
Undefined value {"a": undefined} {"a": null} JSON has no undefined type. Replace undefined values with null or omit the key entirely.
NaN / Infinity {"ratio": NaN} {"ratio": null} JSON numbers do not support NaN (Not a Number) or Infinity. These are JavaScript-specific numeric values.
Unescaped quotes {"msg": "say "hi""} {"msg": "say \"hi\""} A double quote inside a string value must be escaped with a backslash. Otherwise the parser thinks the string has ended.
Unescaped newline {"line": "first
second"}
{"line": "first\nsecond"} Literal newline characters inside strings are not allowed. Use the escape sequences \n (newline), \t (tab), \r (carriage return).
Duplicate keys {"a": 1, "a": 2} {"a": 2} Technically not a parse error, but behaviour is undefined — different parsers handle it differently. Most keep the last value. Avoid duplicate keys entirely.
The trailing comma is the most common JSON bug. JavaScript developers are especially prone to this because trailing commas are valid in modern JavaScript objects and arrays. When copying a JavaScript object literal and pasting it as JSON, always check for and remove trailing commas after the last property or array element.

JSON Formatting vs Minifying — When to Use Each

Formatted (pretty-printed) JSON and minified JSON contain identical data — the only difference is whitespace. The choice between them is purely contextual. Understanding the tradeoffs helps you optimize your applications and APIs. For JSON transmitted via URLs, remember to use our URL encoder to safely escape the formatted or minified string.

When to use formatted JSON

Use formatted JSON when humans need to read and understand the data. The primary use cases are during development (reading API responses, inspecting data structures, writing configuration files manually), in version control (formatted JSON diffs are readable in git; minified JSON diffs are essentially unreadable), in documentation (code examples in API documentation should always be formatted), and in debugging sessions where you need to understand a complex nested structure.

When to use minified JSON

Use minified JSON in production environments where transfer speed and file size matter. A well-written API should return minified JSON in production responses. The size reduction from minification is typically 20–40% depending on how deeply nested and string-heavy the data is. For a response that is called thousands of times per day, this translates to meaningful bandwidth savings and faster response times. This is especially important when your API is accessed over cellular networks or when you're optimizing page performance alongside other tools like CSS minifiers.

Real-world size comparison: A 1KB formatted JSON response (typical for a simple API object) becomes approximately 700 bytes when minified — a 30% reduction. Over 1 million API calls per day, this saves 300MB of daily bandwidth. For larger responses (10KB+), the savings compound significantly.

JSON vs XML vs CSV — Format Comparison

Understanding how JSON compares to other data formats helps you choose the right format for your project. When working with multiple formats, you may need to convert between them or process them using specialized tools. Our URL encoder/decoder helps when any of these formats are transmitted through URLs or APIs.

FeatureJSONXMLCSV
VerbosityLow — minimal syntax overheadHigh — opening and closing tagsMinimal — commas only
ReadabilityHigh when formattedModerate — tags clutter contentLow for nested data
Data types6 native typesString only (types must be parsed)String only
Hierarchical dataExcellent — nested objects/arraysExcellent — nested elementsNone — flat only
Parse speedFastSlow — more markup to parseVery fast
Schema validationJSON Schema, OpenAPIXSD, DTD (mature ecosystem)Limited
CommentsNot supportedSupportedNot standardised
Browser native supportYes — JSON.parse()Yes — DOMParserNo — requires library
Best forAPIs, config, NoSQLDocument markup, SOAP, SVGTabular data, spreadsheets

How to Format JSON Programmatically — Language Reference

This online tool is ideal for one-off formatting and debugging. For programmatic formatting in your codebase, here is the correct approach in every major language. When JSON is transmitted in URLs (such as API parameters), use our URL encoder to safely escape the formatted JSON string.

JavaScript / Node.js

JSON.stringify() accepts a third argument for indentation. Pass a number for space-based indentation or a string (e.g. "\t") for tab-based indentation. The second argument is a replacer — pass null to include all properties.

// Format with 2-space indentation const obj = { name: "Alice", age: 28 }; const formatted = JSON.stringify(obj, null, 2); console.log(formatted); // Minify const minified = JSON.stringify(obj); // Parse JSON string back to object const parsed = JSON.parse('{"name":"Alice"}');

Python

Python's built-in json module handles formatting via the indent parameter of json.dumps(). Use sort_keys=True to alphabetically sort keys — useful for consistent diffing in version control.

import json data = {"name": "Alice", "age": 28} # Format with 4-space indentation formatted = json.dumps(data, indent=4, sort_keys=True) print(formatted) # Minify minified = json.dumps(data, separators=(',', ':')) # Parse JSON string to dict parsed = json.loads('{"name":"Alice"}')

PHP

<?php $data = ["name" => "Alice", "age" => 28]; // Format $formatted = json_encode($data, JSON_PRETTY_PRINT); // Minify $minified = json_encode($data); // Parse $parsed = json_decode('{"name":"Alice"}', true);

Java (Jackson)

ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); // Serialize object to formatted JSON String formatted = mapper.writeValueAsString(myObject); // Or use writerWithDefaultPrettyPrinter String pretty = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(myObject);

Command line (jq)

jq is the standard command-line JSON processor. It formats JSON by default and supports powerful filtering, transformation, and querying of JSON data.

# Format a JSON file jq '.' input.json # Format and save to new file jq '.' input.json > output.json # Minify jq -c '.' input.json # Extract a nested value jq '.user.name' input.json

JSON Schema — Validating Structure and Data Types

Basic JSON validation (which this tool performs) only checks that the JSON is syntactically correct. JSON Schema goes further — it validates that a JSON document has the correct structure, the right data types for each field, required keys, value constraints (minimum, maximum, pattern matching), and more. JSON Schema is particularly important in API development where you need to guarantee that client-submitted data matches the expected format before processing it. For API requests, always validate JSON payloads here first, then use our URL encoder if you're passing JSON as query parameters, or our Base64 encoder for encoding binary data embedded in JSON. Here is a simple JSON Schema example for validating a user object:

{ "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "required": ["name", "email"], "properties": { "name": { "type": "string", "minLength": 1 }, "email": { "type": "string", "format": "email" }, "age": { "type": "integer", "minimum": 0, "maximum": 150 } } }

Advanced JSON Topics — JSONPath, JSONC, and JSON5

JSONPath — querying JSON like XPath queries XML

JSONPath is a query language for JSON that lets you extract specific values from a complex nested structure using path expressions. It is similar in concept to XPath for XML and is supported in libraries for JavaScript, Python, Java, PHP, and most other major languages. When combined with our URL encoder, JSONPath queries can be safely transmitted in API URLs.

Common JSONPath expressions: $.name extracts the root-level "name" property. $.users[0].email extracts the email of the first user. $.users[*].name extracts all user names. $.store..price extracts all prices anywhere in the store object using deep scan. JSONPath is widely used in API testing tools (Postman uses JSONPath for test assertions), configuration management tools, and data pipeline transformations.

JSONC — JSON with Comments

JSONC is an extension of JSON that supports JavaScript-style comments (// and /* */). It is used in configuration files where comments explaining settings are important — most notably in tsconfig.json (TypeScript compiler configuration) and VS Code's settings.json. JSONC files are not valid standard JSON and cannot be parsed by standard JSON parsers — they require a JSONC-aware parser. If you paste JSONC into this tool, it will show as invalid because this tool uses the standard JSON specification. For data that needs to be transmitted via URL parameters, convert to standard JSON first.

JSON5 — JSON for Humans

JSON5 is a more relaxed superset of JSON designed for hand-written configuration files. In addition to JSONC comments, JSON5 also allows: single-quoted strings, unquoted object keys (if they are valid JavaScript identifiers), trailing commas in objects and arrays, hexadecimal numbers (0xFF), and multi-line strings. JSON5 is used by Babel configuration files, some ESLint configurations, and build tools. Like JSONC, it is not valid standard JSON and requires a dedicated parser. When sharing JSON5 configs with other developers, consider converting to standard JSON using this formatter, then share via URL-encoded link parameters or Base64-encoded content.

Important: Never use JSONC or JSON5 for API responses or data interchange between systems. Use them only for developer-facing configuration files where a compatible parser is guaranteed. Standard JSON is the only format with universal parser support across all languages and environments.

JSON in APIs — REST, GraphQL, and Webhooks

REST APIs

REST APIs almost universally use JSON as their data interchange format. A typical REST API response includes a Content-Type: application/json header and returns a minified JSON body. When building or consuming REST APIs, correctly formatted JSON is critical — sending malformed JSON in a request body will cause the server to return a 400 Bad Request error. Before debugging why an API integration is failing, paste the request body into this formatter to verify it is valid JSON. When working with query parameters in APIs, use our URL encoder to properly format API endpoint parameters.

Webhooks

Webhooks send JSON payloads to your endpoint via HTTP POST when events occur — for example, when a Stripe payment completes, when a GitHub push is made, or when a Shopify order is placed. The payload is always minified JSON for efficient transmission. When debugging a webhook that is not processing correctly, copy the raw webhook body and paste it into this formatter to inspect the structure and identify which fields contain the data you need. If the webhook includes encoded data (such as Base64-encoded authentication tokens or URL-encoded parameters), decode them using our specialized tools.

GraphQL responses

GraphQL APIs always return JSON, even when the request uses GraphQL query language syntax. The response always has the structure {"data": {...}, "errors": [...]}. The data field contains the requested data (or null on error). The errors field is omitted when there are no errors. Formatting GraphQL responses with this tool makes it much easier to understand which part of the nested data structure corresponds to which part of your query. For APIs using authentication, ensure your API keys and bearer tokens are properly encoded using our Base64 encoder when needed.

How to Use This JSON Formatter

  1. Paste your JSON into the left input panel. The character count updates as you type.
  2. Click Format JSON to beautify and validate simultaneously. Valid JSON appears in the right panel with syntax highlighting. Invalid JSON shows an error message with the exact position.
  3. Click Minify to strip all whitespace and produce the smallest possible JSON string.
  4. Click Validate to check validity without changing the formatting.
  5. Switch indentation between 2 spaces and 4 spaces using the buttons next to the controls.
  6. Check the status bar for key count, nesting depth, and file size.
  7. Copy or Download the formatted output using the buttons in the output panel header.
  8. Click Load sample to see a realistic example JSON structure if you want to explore the tool.

Related Developer Tools

Frequently Asked Questions

What is JSON and why do developers use it?+
JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format specified in ECMA-404 and RFC 8259. Developers use it because it is human-readable when formatted, natively supported in all major programming languages, significantly more compact than XML, and maps naturally to the data structures (objects and arrays) found in virtually every programming language. It is the dominant format for REST API responses, webhook payloads, NoSQL databases, and configuration files. When APIs return JSON responses containing URLs or encoded data, use our URL encoder and Base64 encoder to handle special characters properly.
What is the difference between formatting and minifying JSON?+
Formatting adds indentation, line breaks, and spacing to make JSON readable for humans. Minifying strips all unnecessary whitespace to produce the smallest possible file size. Both versions contain identical data — only whitespace differs. Use formatted JSON during development and debugging. Use minified JSON in production API responses and configuration files where transfer speed and file size matter.
Why does my JSON show as invalid when it looks correct?+
JSON has extremely strict syntax rules. The most common causes are: single quotes instead of double quotes (JSON requires double quotes only), a trailing comma after the last item in an object or array (JavaScript allows this; JSON does not), JavaScript-style comments (JSON supports no comments), unquoted object keys, undefined or NaN values (not valid JSON types), and unescaped double quotes or backslashes inside string values. The error message in this tool shows the exact line and character position of the problem. If your JSON contains URLs or encoded data, validate it in raw form before using our URL encoder or Base64 encoder to process specific fields.
Is this JSON formatter safe for sensitive data?+
Yes. This formatter runs entirely in your browser using JavaScript. Your JSON data is never transmitted to any server and is never logged or stored anywhere. You can verify this by opening your browser's Developer Tools, going to the Network tab, and confirming that no network requests are made when you format or validate JSON. It is safe to use with API keys, authentication tokens (whether in plain text or Base64-encoded), customer data, and any other sensitive information.
Does JSON support comments?+
No. The official JSON specification does not allow comments of any kind — neither // single-line comments nor /* */ block comments. Douglas Crockford intentionally excluded comments from the JSON specification. If you need JSON with comments for configuration files, consider JSONC (used in TypeScript configs and VS Code settings) or JSON5. These are not valid standard JSON and require dedicated parsers, but they are appropriate for developer-facing configuration files. For public APIs and data interchange, always use standard JSON validated with this formatter.
What are the valid data types in JSON?+
JSON supports exactly six data types: string (double-quoted), number (integer or decimal, no NaN or Infinity), boolean (true or false, must be lowercase), null (must be lowercase), object (key-value pairs in curly braces, all keys must be strings in double quotes), and array (ordered list in square brackets). JSON does not support dates (use ISO 8601 strings), functions, undefined, NaN, Infinity, or binary data. For binary data in JSON APIs, use Base64 encoding to represent binary values as strings.
How do I format JSON in Python, JavaScript, and PHP?+
JavaScript: JSON.stringify(obj, null, 2) formats with 2-space indentation. Python: json.dumps(dict, indent=4) formats with 4 spaces. PHP: json_encode($array, JSON_PRETTY_PRINT) formats with 4 spaces. Java with Jackson: mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object). Command line: jq '.' input.json formats any JSON file. These all produce output identical to what this online tool generates. When transmitting formatted JSON through APIs or URLs, use our URL encoder to safely escape special characters.
What is the maximum size of JSON this tool can handle?+
This tool runs in your browser and is limited by your browser's JavaScript engine memory and the textarea input limits. In practice it handles JSON files up to several megabytes without issues on modern hardware. For very large JSON files (50MB+), consider using a command-line tool like jq which is optimised for large file processing and has no browser memory constraints.
Advertisement Banner (728x90)