JSON Formatter Online Free — Beautify, Minify & Validate JSON
JSON has become the universal language of data exchange — every REST API, configuration file, and web application speaks it. The free JSON Formatter on PublicSoftTools formats, validates, and minifies JSON instantly in your browser. This guide explains how JSON works, how to use the formatter effectively, and how to diagnose every common JSON error.
What is JSON?
JSON stands for JavaScript Object Notation. It is a lightweight, text-based data interchange format defined by RFC 8259. Despite the name, JSON is language-independent — it is supported natively in Python, Ruby, Java, Go, Rust, Swift, C#, and virtually every other programming language. The format was created by Douglas Crockford in the early 2000s as a simpler alternative to XML for transmitting structured data between a server and a web browser.
JSON's success is largely due to its readability and simplicity. A JSON document looks like plain text that humans can read and machines can parse with minimal overhead. Compare a JSON object to its XML equivalent:
// JSON
{"name": "Alice", "age": 30, "active": true}
<!-- XML equivalent -->
<user>
<name>Alice</name>
<age>30</age>
<active>true</active>
</user>JSON transmits the same data in roughly half the bytes, with no closing tags to maintain and no attribute syntax to remember. This simplicity, combined with native JavaScript parsing via JSON.parse() and JSON.stringify(), made JSON the dominant format for web APIs by 2010 — a position it has held ever since.
Today JSON is found everywhere: REST API responses, configuration files (package.json, tsconfig.json, .eslintrc.json), database storage (PostgreSQL JSONB columns, MongoDB documents), log formats, message queues, and data pipelines. Understanding JSON deeply is a foundational skill for any developer.
JSON Data Types — The Complete Reference
JSON supports exactly six data types. Every valid JSON value must be one of these:
1. String
A sequence of Unicode characters enclosed in double quotes. Strings must use double quotes — single quotes are not valid in JSON. Certain characters require escape sequences:
{
"name": "Alice Müller",
"path": "C:\\Users\\Alice",
"quote": "She said \"hello\"",
"newline": "Line 1\nLine 2",
"tab": "col1\tcol2",
"unicode": "\u00e9"
}The escape sequences you need to know:
| Sequence | Meaning |
|---|---|
\\" | Double quote |
\\\\ | Backslash |
\\/ | Forward slash (optional) |
\\n | Newline |
\\r | Carriage return |
\\t | Tab |
\\uXXXX | Unicode code point (4 hex digits) |
2. Number
JSON numbers include integers and floating-point values. There is no distinction between int and float at the type level — both are simply numbers. Notable restrictions: no leading zeros (except 0.5), no trailing decimal point, no infinity, and no NaN. Scientific notation is valid:
{
"integer": 42,
"negative": -7,
"float": 3.14159,
"scientific": 1.5e10,
"small": 2.5e-3
}A critical precision caveat: JSON numbers that exceed JavaScript's safe integer range (±2⁵³) can lose precision when parsed by JavaScript engines. For large integer IDs (such as Twitter tweet IDs or database primary keys over 9 quadrillion), encode them as strings to avoid silent precision loss.
3. Boolean
The literals true and false (lowercase only). UppercaseTrue or False are not valid JSON — a common mistake for developers coming from Python.
4. Null
The literal null (lowercase only) represents an intentionally absent value. Use null when a field exists but has no value, as opposed to omitting the field entirely. The distinction matters when merging or patching JSON objects.
5. Object
An unordered collection of key-value pairs enclosed in curly braces. Keys must be strings (double-quoted). Values can be any JSON type, including nested objects and arrays. The specification does not define order, though most parsers preserve insertion order.
{
"user": {
"id": 1,
"name": "Alice",
"address": {
"city": "Berlin",
"country": "DE"
}
}
}6. Array
An ordered sequence of values enclosed in square brackets. Array items can be any JSON type and do not need to be the same type:
{
"tags": ["developer", "open-source"],
"scores": [98, 87, 92],
"mixed": [1, "two", true, null, {"nested": "object"}]
}Why Format JSON?
JSON produced by APIs and tools is typically minified — compressed onto a single line with all whitespace removed to minimize payload size. This is ideal for machines but impossible for humans to read. Formatting (also called pretty-printing or beautifying) adds indentation and line breaks to make the structure visible.
The difference is dramatic. Here is the same data minified vs formatted:
// Minified (machine-friendly)
{"user":{"id":1,"name":"Alice","roles":["admin","editor"],"settings":{"theme":"dark","notifications":true}}}// Formatted (human-readable)
{
"user": {
"id": 1,
"name": "Alice",
"roles": [
"admin",
"editor"
],
"settings": {
"theme": "dark",
"notifications": true
}
}
}Formatting is essential for: debugging API responses, understanding unfamiliar data structures, writing documentation, reviewing data in pull requests, and diagnosing serialization bugs. A good JSON formatter makes all of these tasks faster.
How to Use the JSON Formatter Tool
The PublicSoftTools JSON Formatter provides four core functions: format, minify, validate, and copy. Here is how to use each:
- Paste your JSON — Copy the JSON you want to format from your API response, log file, config file, or clipboard and paste it into the input area. The formatter accepts JSON of any size.
- Choose indentation — Select 2-space indentation (common in JavaScript and web projects) or 4-space indentation (common in Python and Java codebases). Tab indentation is also available for codebases that use tabs over spaces.
- Click Format — The formatter parses your JSON, validates the syntax, and produces a pretty-printed version with consistent indentation and line breaks.
- Review errors — If your JSON has a syntax error, the formatter displays the error message with the line number and character position. Fix the error in the input and format again.
- Minify if needed — Click Minify to produce the most compact version of your JSON, suitable for API payloads, database storage, or production configuration.
- Copy the result — Click Copy to copy the formatted or minified output directly to your clipboard, ready to paste wherever you need it.
All processing happens in your browser using the built-in JSON.parse() and JSON.stringify() JavaScript functions. Your data never leaves your device.
Common JSON Syntax Errors and How to Fix Them
The JSON specification is strict. A single misplaced comma or missing quote renders the entire document invalid. These are the errors you will encounter most often:
Trailing Commas
Standard JSON does not allow a comma after the last item in an object or array. This is valid JavaScript (and JSONC) but invalid JSON:
// INVALID — trailing comma after last value
{
"name": "Alice",
"age": 30,
}// VALID
{
"name": "Alice",
"age": 30
}This is the most common JSON error, especially when editing JSON by hand or when converting JavaScript object literals to JSON.
Single Quotes
JSON requires double quotes for all strings — both keys and values. Single quotes produce a parse error:
// INVALID
{'name': 'Alice'}
// VALID
{"name": "Alice"}Unquoted Keys
JavaScript object literals allow unquoted keys ({ name: 'Alice' }), but JSON does not. Every key must be a quoted string:
// INVALID (JavaScript syntax, not JSON)
{name: "Alice", age: 30}
// VALID JSON
{"name": "Alice", "age": 30}Comments
JSON does not support comments of any kind — neither // single-line nor /* */ block comments. If you need annotated configuration files, use JSONC (JSON with Comments, supported by VS Code and TypeScript's tsconfig.json), YAML, or TOML. When passing JSON to an API or parser, always strip comments first.
// INVALID — comments not allowed in JSON
{
// This is the user's name
"name": "Alice"
}Undefined and Special Values
JavaScript has undefined, Infinity, -Infinity, and NaN — none of which are valid JSON values. If your serializer produces these, you will need to handle them before encoding:
// INVALID
{"score": NaN, "ratio": Infinity, "value": undefined}
// VALID — replace with null or omit the field
{"score": null, "ratio": null}Duplicate Keys
The JSON specification does not forbid duplicate keys in an object, but the behavior is undefined — different parsers handle it differently (last-wins, first-wins, error). In practice, treat duplicate keys as a bug and deduplicate them.
Encoding Errors
JSON must be encoded in Unicode (UTF-8, UTF-16, or UTF-32). The most common encoding issue is a file saved as Latin-1 or Windows-1252 that contains non-ASCII characters — accented letters, em dashes, or curly quotes — that are not valid UTF-8 bytes. Re-save the file as UTF-8 to fix this.
JSON vs XML vs YAML vs TOML
JSON competes with several other data formats. Here is when each one is the right choice:
| Format | Verbosity | Comments | Schema Support | Best Use Case |
|---|---|---|---|---|
| JSON | Low | No | JSON Schema | REST APIs, config files, data exchange |
| XML | High | Yes | XSD, DTD, RelaxNG | Enterprise integrations, SOAP APIs, document markup |
| YAML | Medium | Yes (#) | JSON Schema (via libraries) | CI/CD configuration, Kubernetes, human-edited config |
| TOML | Low–Medium | Yes (#) | Limited | Application config (Rust Cargo.toml, Python pyproject.toml) |
| CSV | Very Low | No | None standard | Tabular data, spreadsheet import/export |
For converting between formats, the XML to JSON Converter and JSON to CSV Converter handle the most common transformation needs.
JSON in REST APIs
The vast majority of modern REST APIs use JSON for both request bodies and response payloads. When working with JSON APIs, understanding the HTTP context is important:
Request headers: When sending JSON in a request body (POST, PUT, PATCH), include Content-Type: application/json so the server knows how to parse the body. When requesting a JSON response, include Accept: application/json.
POST /api/users HTTP/1.1
Content-Type: application/json
Accept: application/json
{
"name": "Alice",
"email": "alice@example.com"
}HTTP status codes with JSON errors: APIs typically return error information as JSON even when the status code indicates failure. A well-designed error response looks like:
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
{
"error": "validation_failed",
"message": "Email address is already in use",
"field": "email",
"code": 1042
}When debugging API interactions, paste the raw JSON response into the formatter to make the error structure readable. Pay particular attention to nested error arrays, which APIs use to report multiple validation failures in a single response.
Pagination: APIs that return large datasets use JSON pagination patterns. The two most common are cursor-based pagination (a next_cursor token) and offset-based pagination (page and per_page):
{
"data": [...],
"pagination": {
"page": 2,
"per_page": 50,
"total": 847,
"next_cursor": "eyJpZCI6IDEwMH0"
}
}JSON Schema — Validating Structure and Types
JSON Schema is a vocabulary for annotating and validating JSON documents. It lets you define the expected structure of a JSON object — which fields are required, what type each field must be, allowed values, string length constraints, and more. JSON Schema documents are themselves written in JSON.
A basic JSON Schema for a user object:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"id": {
"type": "integer",
"minimum": 1
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"email": {
"type": "string",
"format": "email"
},
"role": {
"type": "string",
"enum": ["admin", "editor", "viewer"]
},
"active": {
"type": "boolean"
}
},
"required": ["id", "name", "email", "role"]
}JSON Schema is used in API documentation (OpenAPI/Swagger specs embed JSON Schema), form validation libraries, code generation tools, and IDE autocompletion for JSON config files. TypeScript projects use JSON Schema to validate API contracts at the boundary between the network and application code.
Working With Large JSON Files
Browser-based JSON parsers load the entire document into memory before processing. For files over a few megabytes, this can cause performance issues or browser tab crashes. Strategies for handling large JSON:
- Command-line jq: The
jqtool is the gold standard for large JSON. It streams through files without loading everything into memory. Query example:jq '.users[].name' large-data.jsonextracts all user names without loading the full array. - Streaming parsers: Languages like Python offer streaming JSON parsers (
ijson) that process records one at a time. Node.js hasstream-jsonfor similar use. - JSON Lines (JSONL): For datasets of many JSON objects, JSON Lines format (one JSON object per line) is more streaming-friendly than a single large JSON array. Each line is independently parseable.
- Database import: For JSON files over 100 MB, consider importing into PostgreSQL (which has excellent JSONB support) or MongoDB and querying there rather than loading in a browser or script.
JSON Parsing in Different Programming Languages
Every major programming language includes JSON parsing in its standard library or as a commonly bundled package. Here are the canonical patterns:
JavaScript / Node.js
// Parse JSON string to object
const obj = JSON.parse('{"name": "Alice", "age": 30}');
console.log(obj.name); // "Alice"
// Serialize object to JSON string
const json = JSON.stringify(obj, null, 2); // null = no replacer, 2 = indent spaces
// Async file reading in Node.js
import { readFile } from 'fs/promises';
const data = JSON.parse(await readFile('data.json', 'utf8'));Python
import json
# Parse JSON string
data = json.loads('{"name": "Alice", "age": 30}')
print(data["name"]) # Alice
# Serialize to JSON
json_str = json.dumps(data, indent=2)
# Read/write JSON files
with open("data.json") as f:
data = json.load(f)
with open("output.json", "w") as f:
json.dump(data, f, indent=2)Java
// Using Jackson (most popular library)
ObjectMapper mapper = new ObjectMapper();
// Parse JSON string to Map
Map<String, Object> data = mapper.readValue(jsonString, Map.class);
// Parse to typed class
User user = mapper.readValue(jsonString, User.class);
// Serialize to JSON
String json = mapper.writeValueAsString(user);
String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);C#
using System.Text.Json;
// Parse JSON string
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var user = JsonSerializer.Deserialize<User>(jsonString, options);
// Serialize to JSON
string json = JsonSerializer.Serialize(user);
string prettyJson = JsonSerializer.Serialize(user, new JsonSerializerOptions { WriteIndented = true });Pretty-Print vs Minify: When to Use Each
| Mode | Output | Use Case |
|---|---|---|
| Pretty-print (2-space) | Indented, readable | Debugging, reading API responses, documentation |
| Pretty-print (4-space) | Indented, more spacious | Code files, config files, team style preferences |
| Minify | No whitespace, single line | Production API payloads, embedded config, reducing bandwidth |
JSON Security Considerations
JSON is a data format, not code — but JSON handling can introduce security vulnerabilities if done carelessly. Key risks to be aware of:
- JSON injection: When building JSON strings by concatenation rather than serialization, user input containing quotes or brackets can break out of the intended context. Always use a proper JSON serializer, never string concatenation.
- Excessive nesting / billion laughs: A deeply nested JSON document (hundreds of levels deep) can cause stack overflow errors in recursive parsers. Set a maximum nesting depth in production parsers for untrusted input.
- Large payload attacks: A JSON document containing a huge array of large strings can exhaust server memory. Set request body size limits in your web framework (Express, Django, etc.).
- eval() is never safe for parsing JSON: Using
eval()to parse JSON in JavaScript executes arbitrary code. Always useJSON.parse().
Frequently Asked Questions
What is the difference between JSON and JSONP?
JSONP (JSON with Padding) was a legacy technique for making cross-origin requests before CORS (Cross-Origin Resource Sharing) was standardized. It wrapped JSON in a function call (callback({"data": "..."})) and injected it via a script tag. JSONP is a security risk and should not be used in modern applications — CORS handles cross-origin data fetching safely.
Can JSON contain binary data like images?
JSON is a text format and cannot natively represent binary data. Binary files are typically encoded as Base64 strings and embedded in JSON. The Base64 encoding increases the data size by approximately 33%, so for large binary payloads, multipart form data or binary protocols like Protocol Buffers are more efficient.
Does JSON preserve the order of object keys?
The JSON specification does not guarantee key order — objects are defined as unordered sets of key-value pairs. In practice, most modern parsers and engines (V8, Python's json module from Python 3.7+) preserve insertion order, but you should not rely on this for correctness. If order matters, use an array of key-value pairs instead.
What is JSONC?
JSONC (JSON with Comments) is a superset of JSON that allows single-line (//) and block (/* */) comments. It is used in VS Code's settings files, TypeScript's tsconfig.json, and some other tooling configuration formats. JSONC files cannot be parsed by standard JSON parsers — use a JSONC-aware parser or strip comments before parsing.
Is JSON.parse() safe for untrusted input?
Yes — JSON.parse() is safe. Unlike eval(), it only parses the JSON data model and cannot execute code. However, you should still validate thestructure and values of parsed JSON from untrusted sources using JSON Schema or manual validation, since a syntactically valid JSON document may contain semantically invalid data.
What is the maximum size JSON file a browser can handle?
Modern browsers can parse JSON files up to about 50–100 MB before hitting memory or performance issues. The practical limit depends on available RAM and the browser engine. For files larger than 10 MB, consider server-side processing or the command-line jq tool. For the browser-based formatter, files under 5 MB work instantly; files between 5–20 MB may take a few seconds.
Format and Validate JSON Free Online
Pretty-print, minify, and validate syntax instantly. No signup, browser-based.
Open JSON Formatter