JSON formatter and JSON validator tools are essential for every developer working with APIs, configuration files, and data interchange. Whether you need to format JSON for readability, validate JSON online to catch syntax errors, or pretty print JSON for debugging, this comprehensive guide covers everything you need to know. JSON (JavaScript Object Notation) has become the universal language of web data, and mastering how to format, validate, and debug it is a fundamental skill. Our free json formatter online tool handles formatting, validation, minification, and syntax error detection instantly in your browser.
Try our free JSON Formatter & Validator tool instantly.
What Is JSON?
JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. Originally derived from JavaScript, JSON is now language-independent and supported by virtually every programming language. It has become the de facto standard for data exchange in web APIs, configuration files, and NoSQL databases.
A JSON document consists of two primary structures: objects (unordered collections of key-value pairs wrapped in curly braces {}) and arrays (ordered lists of values wrapped in square brackets []). Values can be strings (in double quotes), numbers, booleans (true/false), null, objects, or arrays. This simplicity is what makes JSON so versatile and widely adopted.
JSON is defined by two standards: RFC 8259 (the IETF specification) and ECMA-404 (the ECMA International specification). The official media type is application/json, and the file extension is .json. Unlike XML, JSON has no built-in support for comments, namespaces, or attributes, which keeps the format minimal and parsing fast.
Why You Need a JSON Formatter
Readability: Raw JSON from APIs and databases is often a single long line with no whitespace. A JSON formatter (also called a JSON beautifier or pretty print JSON tool) adds proper indentation and line breaks so you can visually parse nested structures. This makes it dramatically easier to understand complex data responses from REST APIs.
Debugging: When something goes wrong with an API response or a configuration file, the first step is often to format JSON and inspect the structure. A JSON validator identifies the exact location of syntax errors, helping you pinpoint missing commas, mismatched brackets, or invalid values in seconds rather than minutes of manual inspection.
Validation: Before deploying configuration files, sending API payloads, or storing data, you should always validate JSON online to ensure it conforms to the specification. Invalid JSON can cause silent failures in applications, corrupt data pipelines, and trigger hard-to-debug production issues. A json lint tool catches these problems before they reach production.
Minification: When transmitting JSON over the network, you want to minify JSON by removing all unnecessary whitespace. This reduces payload sizes, speeds up API responses, and decreases bandwidth costs. Our tool lets you switch between formatted and minified output with a single click.
Common JSON Syntax Errors
A JSON syntax error can break your entire application. Here are the most frequent mistakes developers make and how to fix them:
Trailing commas: JSON does not allow a comma after the last item in an object or array. {"a": 1, "b": 2,} is invalid. Remove the trailing comma: {"a": 1, "b": 2}. This is the single most common json syntax error because many programming languages do allow trailing commas.
// INVALID: trailing comma
{
"name": "John",
"age": 30,
}
// VALID: no trailing comma
{
"name": "John",
"age": 30
}Single quotes instead of double quotes: JSON requires double quotes for all strings and keys. {'name': 'John'} is invalid. Use double quotes: {"name": "John"}. This mistake is common when copying data from Python dictionaries or JavaScript objects.
// INVALID: single quotes
{'name': 'John', 'age': 30}
// VALID: double quotes
{"name": "John", "age": 30}Unquoted keys: Every key in a JSON object must be a double-quoted string. {name: "John"} is invalid. Correct form: {"name": "John"}. JavaScript allows unquoted keys, but JSON does not.
Comments in JSON: Standard JSON does not support comments. {"name": "John" /* comment */} is invalid. If you need comments, consider using JSONC (JSON with Comments) supported by VS Code, or move to YAML or TOML for configuration files.
// INVALID: comments not allowed in JSON
{
"name": "John", // this is a comment
"age": 30 /* block comment */
}
// VALID: no comments
{
"name": "John",
"age": 30
}Using undefined or NaN: JSON only supports null, not undefined, NaN, or Infinity. These JavaScript-specific values must be converted before serialization. Use null as a replacement for undefined values.
// INVALID in JSON (JavaScript-specific values)
{
"value1": undefined,
"value2": NaN,
"value3": Infinity
}
// VALID: use null instead
{
"value1": null,
"value2": null,
"value3": null
}Missing or extra brackets/braces: Every opening { or [ must have a matching closing } or ]. Deeply nested structures make this error easy to introduce. A json validator highlights exactly which bracket is unmatched.
Invalid escape sequences: JSON strings support specific escape sequences: \", \\, \/, \b, \f, \n, \r, \t, and \uXXXX. Using other backslash sequences like \a or \x41 is a json syntax error.
How to Format JSON
There are several ways to format JSON depending on your workflow. Here are the most popular methods:
Online JSON formatter: The fastest way to format JSON online is to paste your data into our free JSON formatter tool. It instantly validates, formats, and highlights syntax errors with line numbers. No installation required, works entirely in your browser.
Command line with jq: jq is the most powerful command-line JSON processor. Install it via brew install jq (macOS), apt install jq (Ubuntu), or choco install jq (Windows). Then use echo '{"a":1}' | jq . to pretty print JSON in the terminal.
Python built-in module: Python ships with a JSON formatter: python -m json.tool file.json. You can also pipe data: echo '{"a":1}' | python -m json.tool. For more control, use json.dumps(data, indent=2) in your Python scripts.
IDE extensions: VS Code has built-in JSON formatting (Shift+Alt+F / Shift+Option+F). JetBrains IDEs (IntelliJ, WebStorm) offer Code > Reformat Code (Ctrl+Alt+L). Vim users can use :%!jq . or :%!python -m json.tool.
Browser DevTools: Chrome, Firefox, and Edge DevTools automatically format JSON responses in the Network tab preview. You can also type JSON.stringify(obj, null, 2) in the console to pretty print JSON any JavaScript object.
JSON Validation Rules
To properly validate JSON, you need to understand the exact specification. Here are the rules defined by RFC 8259:
Data types: JSON supports exactly six data types: string (double-quoted Unicode text), number (integer or floating point, no leading zeros, no hex/octal), boolean (true or false, lowercase only), null (lowercase only), object (unordered key-value pairs), and array (ordered list of values).
// All six JSON data types demonstrated:
{
"string": "Hello World",
"number": 42.5,
"boolean": true,
"nullValue": null,
"object": {
"nested": "value"
},
"array": [1, "two", false, null, {"key": "val"}, [1,2,3]]
}Strings: Must be enclosed in double quotes. May contain any Unicode character except unescaped control characters (U+0000 through U+001F). Backslash escapes are: \" \\ \/ \b \f \n \r \t \uXXXX.
Numbers: May be integer or floating point. Scientific notation is allowed (1.5e10). Leading zeros are not allowed (01 is invalid). NaN, Infinity, and -Infinity are not valid JSON numbers. Hex (0xFF) and octal (0o77) are also invalid.
// Valid JSON numbers:
42 // integer
-17 // negative integer
3.14 // floating point
2.5e10 // scientific notation
-1.23e-4 // negative scientific notation
// INVALID JSON numbers:
01 // leading zero not allowed
.5 // must have digit before decimal
+1 // leading plus not allowed
0xFF // hex not allowed
0o77 // octal not allowed
NaN // not a valid JSON value
Infinity // not a valid JSON valueObjects: Keys must be unique strings (though parsers may handle duplicates differently). The order of key-value pairs is not guaranteed. Empty objects {} are valid.
Arrays: Elements can be of mixed types. Empty arrays [] are valid. Arrays can be nested to arbitrary depth.
Encoding: JSON text must be encoded in UTF-8, UTF-16, or UTF-32, with UTF-8 being the default and most widely used. A Byte Order Mark (BOM) should not be included but some parsers tolerate it.
Top-level value: RFC 8259 allows any JSON value (string, number, boolean, null, object, or array) as the top-level element. Older RFC 4627 required only objects or arrays at the top level.
Code Examples: Format and Validate JSON
JavaScript: Format and Validate JSON
JavaScript provides built-in JSON.parse() and JSON.stringify() methods for JSON validation and formatting. Use JSON.stringify(data, null, 2) to pretty print JSON with 2-space indentation:
// ===== JSON.parse(): Validate JSON =====
// Valid JSON string
const jsonString = '{"name": "Alice", "age": 30, "active": true}';
const data = JSON.parse(jsonString);
console.log(data.name); // "Alice"
// Validate JSON safely with try/catch
function isValidJSON(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
console.error('JSON syntax error:', e.message);
return false;
}
}
isValidJSON('{"valid": true}'); // true
isValidJSON('{invalid: true}'); // false — "Unexpected token i"
isValidJSON('{"trailing": 1,}'); // false — "Unexpected token }"
// ===== JSON.stringify(): Format / Pretty Print JSON =====
const obj = {
name: "Alice",
age: 30,
address: {
city: "New York",
zip: "10001"
},
hobbies: ["reading", "coding", "hiking"]
};
// Pretty print with 2-space indentation
const formatted = JSON.stringify(obj, null, 2);
console.log(formatted);
/*
{
"name": "Alice",
"age": 30,
"address": {
"city": "New York",
"zip": "10001"
},
"hobbies": [
"reading",
"coding",
"hiking"
]
}
*/
// Pretty print with 4-space indentation
console.log(JSON.stringify(obj, null, 4));
// Pretty print with tab indentation
console.log(JSON.stringify(obj, null, "\t"));
// Minify JSON (no whitespace)
const minified = JSON.stringify(obj);
// {"name":"Alice","age":30,"address":{"city":"New York","zip":"10001"},...}
// Custom replacer: filter specific keys
const filtered = JSON.stringify(obj, ["name", "age"], 2);
/*
{
"name": "Alice",
"age": 30
}
*/
// Reviver function: transform values during parsing
const parsed = JSON.parse('{"date": "2025-01-15T00:00:00Z"}', (key, value) => {
if (key === 'date') return new Date(value);
return value;
});
console.log(parsed.date instanceof Date); // truePython: Format and Validate JSON
Python's built-in json module provides json.dumps() with an indent parameter for formatting, and json.loads() for validation. You can also use python -m json.tool from the command line:
import json
# ===== json.loads(): Validate JSON =====
json_string = '{"name": "Alice", "age": 30, "active": true}'
data = json.loads(json_string)
print(data["name"]) # "Alice"
# Validate JSON safely
def is_valid_json(s):
try:
json.loads(s)
return True
except json.JSONDecodeError as e:
print(f"JSON syntax error at line {e.lineno}, col {e.colno}: {e.msg}")
return False
is_valid_json('{"valid": true}') # True
is_valid_json('{invalid: true}') # False
is_valid_json('{"trailing": 1,}') # False
# ===== json.dumps(): Format / Pretty Print JSON =====
data = {
"name": "Alice",
"age": 30,
"address": {
"city": "New York",
"zip": "10001"
},
"hobbies": ["reading", "coding", "hiking"]
}
# Pretty print with 2-space indentation
formatted = json.dumps(data, indent=2)
print(formatted)
# Pretty print with sorted keys
formatted_sorted = json.dumps(data, indent=2, sort_keys=True)
print(formatted_sorted)
# Minify JSON (compact output)
minified = json.dumps(data, separators=(",", ":"))
print(minified)
# {"name":"Alice","age":30,"address":{"city":"New York","zip":"10001"},...}
# Handle non-ASCII characters (useful for i18n)
data_intl = {"city": "Tokyo", "greeting": "Hello"}
print(json.dumps(data_intl, ensure_ascii=False, indent=2))
# Read and format a JSON file
with open("data.json", "r") as f:
data = json.load(f)
with open("data_formatted.json", "w") as f:
json.dump(data, f, indent=2)
# Command line: python -m json.tool
# $ echo '{"a":1,"b":2}' | python -m json.tool
# {
# "a": 1,
# "b": 2
# }Command Line: jq, python, and node
The command line offers several ways to format JSON and validate JSON. Here are the most common tools:
# ===== jq: The Swiss Army knife for JSON =====
# Pretty print JSON
echo '{"name":"Alice","age":30}' | jq .
# {
# "name": "Alice",
# "age": 30
# }
# Minify JSON (compact output)
echo '{
"name": "Alice",
"age": 30
}' | jq -c .
# {"name":"Alice","age":30}
# Extract specific fields
echo '{"name":"Alice","age":30,"city":"NYC"}' | jq '{name, city}'
# {"name": "Alice", "city": "NYC"}
# Format a JSON file
jq . input.json > formatted.json
# Validate JSON (exit code 0 = valid, non-zero = invalid)
echo '{"valid": true}' | jq . > /dev/null 2>&1 && echo "Valid" || echo "Invalid"
echo '{invalid}' | jq . > /dev/null 2>&1 && echo "Valid" || echo "Invalid"
# Sort keys
echo '{"b":2,"a":1,"c":3}' | jq -S .
# {"a": 1, "b": 2, "c": 3}
# ===== python -m json.tool =====
# Format JSON from stdin
echo '{"a":1,"b":2}' | python3 -m json.tool
# Format a JSON file
python3 -m json.tool input.json output.json
# Sort keys
echo '{"b":2,"a":1}' | python3 -m json.tool --sort-keys
# ===== Node.js one-liner =====
# Pretty print JSON
echo '{"a":1,"b":2}' | node -e "process.stdin.resume();let d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>console.log(JSON.stringify(JSON.parse(d),null,2)))"
# Simpler: use node -p
node -p "JSON.stringify({a:1,b:[2,3]}, null, 2)"curl + jq Pipeline
A common workflow is fetching JSON from an API and formatting it instantly using curl piped to jq:
# Fetch and format JSON from a REST API
curl -s https://api.github.com/users/octocat | jq .
# Fetch, extract specific fields, and format
curl -s https://api.github.com/users/octocat | jq '{login, name, bio, public_repos}'
# Fetch and validate (check exit code)
curl -s https://api.example.com/data | jq . > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo "Response is valid JSON"
else
echo "Response is NOT valid JSON"
fi
# POST JSON and format the response
curl -s -X POST https://api.example.com/data \
-H "Content-Type: application/json" \
-d '{"name":"Alice","age":30}' | jq .
# Save formatted JSON to file
curl -s https://api.github.com/users/octocat | jq . > user.json
# Minify before sending (reduce payload size)
DATA=$(jq -c . large-payload.json)
curl -s -X POST https://api.example.com/data \
-H "Content-Type: application/json" \
-d "$DATA" | jq .JSON Best Practices
Follow these best practices to write clean, maintainable, and performant JSON:
Use camelCase for keys: Most JSON APIs and JavaScript conventions use camelCase (firstName, lastName, phoneNumber). Be consistent across your entire API. Some APIs use snake_case (first_name), which is common in Python and Ruby ecosystems. Whatever convention you choose, stick with it throughout your project.
// camelCase (recommended for most APIs)
{
"firstName": "Alice",
"lastName": "Smith",
"phoneNumber": "+1-555-0123",
"isActive": true
}
// snake_case (common in Python/Ruby ecosystems)
{
"first_name": "Alice",
"last_name": "Smith",
"phone_number": "+1-555-0123",
"is_active": true
}Keep nesting shallow: Deeply nested JSON (more than 3-4 levels) becomes hard to read and parse. If your JSON structure is deeply nested, consider flattening it or splitting it into multiple endpoints. Deep nesting also increases memory usage during parsing and can cause stack overflows in recursive parsers.
// BAD: deeply nested (hard to read and parse)
{
"company": {
"departments": {
"engineering": {
"teams": {
"frontend": {
"members": [{"name": "Alice"}]
}
}
}
}
}
}
// BETTER: flattened structure
{
"companyId": "acme",
"departmentId": "engineering",
"teamId": "frontend",
"members": [{"name": "Alice"}]
}Handle large files carefully: For JSON files larger than a few megabytes, avoid loading the entire file into memory. Use streaming parsers like ijson (Python), JSONStream (Node.js), or jq --stream (command line). When you need to minify JSON large files, streaming tools prevent out-of-memory errors.
Use JSON Schema for validation: For production applications, validate JSON payloads against a JSON Schema definition. Libraries like ajv (JavaScript), jsonschema (Python), and json-schema-validator (Java) provide robust schema validation with detailed error messages.
// JSON Schema example for validating user objects
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"name": { "type": "string", "minLength": 1 },
"age": { "type": "integer", "minimum": 0 },
"email": { "type": "string", "format": "email" },
"roles": {
"type": "array",
"items": { "type": "string" },
"minItems": 1
}
},
"required": ["name", "email"]
}Avoid storing binary data: JSON is a text format. If you need to include binary data (images, files), either use Base64 encoding (which increases size by 33%) or store binary data separately and reference it with URLs in your JSON.
Use consistent null handling: Decide whether to omit keys with null values or include them explicitly. Both approaches are valid, but mixing them creates inconsistent APIs. Document your choice and apply it consistently.
JSON vs Alternatives: YAML, TOML, XML
JSON is not the only data serialization format. Here is a quick comparison with the most popular alternatives:
| Feature | JSON | YAML | TOML | XML |
|---|---|---|---|---|
| Readability | Good | Excellent | Excellent | Moderate |
| Comments | No | Yes | Yes | Yes |
| Data types | 6 types | Rich (dates, etc.) | Rich (dates, etc.) | Text only |
| Nesting | Unlimited | Unlimited | Limited | Unlimited |
| Multi-line strings | No | Yes | Yes | Yes (CDATA) |
| Parser support | Universal | Wide | Growing | Universal |
| File size | Small | Smaller | Smallest | Large (verbose) |
| Best for | APIs, data | Config files | Simple config | Documents, SOAP |
Choose JSON for APIs and data interchange where universal parser support is critical. Use YAML for human-edited configuration files where comments and readability matter. Use TOML for simple configuration files (like pyproject.toml or Cargo.toml). Use XML only when required by existing standards (SOAP, RSS, SVG).
Frequently Asked Questions
How do I format JSON online?
To format JSON online, paste your raw JSON into a JSON formatter tool like ours. The tool will automatically validate the syntax, add proper indentation and line breaks, and highlight any errors with line numbers. You can choose between 2-space or 4-space indentation, and switch between formatted (pretty-printed) and minified output. Our tool runs entirely in your browser, so your data never leaves your computer.
What are common JSON syntax errors?
The most common JSON syntax errors are: trailing commas after the last item in an object or array, using single quotes instead of double quotes, unquoted object keys, adding comments (JSON does not support comments), using undefined or NaN values, mismatched or missing brackets and braces, and invalid escape sequences in strings. A JSON validator tool will identify the exact line and character position of each error.
What is the difference between JSON and YAML?
JSON uses curly braces, square brackets, and double quotes for structure, while YAML uses indentation and minimal punctuation. YAML supports comments, multi-line strings, and anchors/aliases for data reuse; JSON does not. JSON is better for machine-to-machine data exchange (APIs, databases) because every parser produces identical output. YAML is better for human-edited configuration files because it is more readable. JSON is a strict subset of YAML, meaning every valid JSON document is also valid YAML.
Mastering JSON formatting and JSON validation is an essential skill for modern developers. Whether you are debugging API responses, writing configuration files, or building data pipelines, understanding how to format JSON, validate JSON, and avoid common JSON syntax errors will save you countless hours. Bookmark this guide for quick reference, and use our free tool for instant formatting and validation.
Format, validate, and minify JSON instantly with our free online tool.