- What Is JSON?
- JSON Syntax Rules
- JSON Data Types
- Common JSON Errors & How to Fix Them
- Beautify vs Minify: When to Use Each
- How to Use a JSON Formatter
- JSON in 6 Programming Languages
- JSONPath: Querying JSON Data
- JSON Schema: Validating JSON Structure
- JSON vs Related Formats
- Frequently Asked Questions
- Quick Reference Summary
JSON (JavaScript Object Notation) is the universal language of web APIs and data exchange. It powers REST APIs, configuration files, NoSQL databases, inter-service communication, and frontend-backend data transfer. If you write code that touches the web, you work with JSON every day.
The problem is that JSON is deceptively strict. A single misplaced comma, an unquoted key, or a stray comment breaks the entire document — and the error message is rarely helpful. This guide covers everything you need to read, write, validate, format, and debug JSON with confidence.
What Is JSON?
JSON is a lightweight, text-based data format derived from JavaScript object syntax — but it is language-independent. Every major programming language has built-in JSON support.
A valid JSON document is either a single object {} or a single array [] at the top level.
{
"name": "Alice",
"age": 30,
"isActive": true,
"scores": [98, 87, 95],
"address": {
"city": "New York",
"zip": "10001"
},
"nickname": null
}
This single example demonstrates all six JSON data types: string, number, boolean, array, object, and null.
JSON Syntax Rules
Valid JSON follows strict rules. Breaking any one of them makes the entire document invalid — there is no "partial" JSON.
The 7 Non-Negotiable Rules
| Rule | ✅ Valid | ❌ Invalid | Why It Matters |
|---|---|---|---|
| Keys must be double-quoted | "name": "Alice" |
name: "Alice" |
Unquoted keys are JavaScript, not JSON |
| Strings use double quotes only | "value" |
'value' |
Single quotes are not valid in JSON |
| No trailing commas | [1, 2, 3] |
[1, 2, 3,] |
Most parsers reject trailing commas |
| No comments | {"x": 1} |
{"x": 1 // note} |
JSON has no comment syntax |
| Booleans are lowercase | true, false |
True, False |
Case-sensitive — uppercase breaks parsing |
| Null is lowercase | null |
Null, NULL |
Same case-sensitivity rule |
| Numbers are unquoted | 42, 3.14 |
"42" |
Quoted numbers become strings, not numbers |
Structure Rules
- Every key-value pair is separated by a colon
: - Multiple pairs or array items are separated by commas
, - Objects are wrapped in curly braces
{} - Arrays are wrapped in square brackets
[] - Nesting depth has no hard limit, but deep nesting (10+ levels) is a design smell
- JSON is always UTF-8 encoded in modern usage
The trailing comma trap: This is the single most common JSON error. It's valid in JavaScript, Python dictionaries, and many config formats — but strictly forbidden in JSON. Every linter and formatter will catch it immediately.
JSON Data Types
JSON supports exactly six data types — no more, no less.
| Type | Example | Notes |
|---|---|---|
| String | "Hello, World!" |
Must use double quotes. Supports Unicode escape: "\u0041" = "A" |
| Number | 42, 3.14, -7, 1.5e10 |
Integer or float. No NaN, Infinity, or hex literals |
| Boolean | true, false |
Lowercase only. No 1/0 substitutes in strict JSON |
| Array | [1, "two", true, null] |
Ordered. Can mix types. Can be empty [] |
| Object | {"key": "value"} |
Unordered key-value pairs. Keys must be unique strings. Can be empty {} |
| Null | null |
Represents intentional absence of value. Lowercase only |
What JSON Does NOT Support
These are common gotchas when coming from JavaScript or Python:
| ❌ Not Supported | Common Workaround |
|---|---|
undefined |
Use null or omit the key entirely |
NaN |
Use null or a sentinel string like "NaN" |
Infinity |
Use null or a large number constant |
| Date objects | Use ISO 8601 string: "2025-06-05T03:28:00Z" |
| Functions | Not serialisable — omit or convert to string |
Comments // or /* */ |
Use a wrapper key: "_comment": "note here" |
| Single quotes | Always use double quotes |
| Trailing commas | Remove them |
| Binary data | Use Base64-encoded string |
Common JSON Errors & How to Fix Them
These are the errors every developer encounters repeatedly. Recognising them on sight saves debugging time.
Error Reference Table
| ❌ Invalid JSON | ✅ Fixed JSON | Error Type |
|---|---|---|
{name: "John", age: 30} |
{"name": "John", "age": 30} |
Unquoted keys |
{"name": "John", "age": 30,} |
{"name": "John", "age": 30} |
Trailing comma in object |
{"data": [1, 2, 3,]} |
{"data": [1, 2, 3]} |
Trailing comma in array |
{'key': 'value'} |
{"key": "value"} |
Single quotes |
{"active": True} |
{"active": true} |
Uppercase boolean |
{"score": Null} |
{"score": null} |
Uppercase null |
{/* config */ "x": 1} |
{"x": 1} |
Comment in JSON |
{"path": "C:\Users\file"} |
{"path": "C:\\Users\\file"} |
Unescaped backslash |
{"text": "line1\nline2"} |
{"text": "line1\\nline2"} |
Literal newline in string |
{"val": .5} |
{"val": 0.5} |
Leading decimal point |
String Escape Sequences
Inside JSON strings, certain characters must be escaped with a backslash:
| Character | Escaped Form | Meaning |
|---|---|---|
" |
\" |
Double quote |
\ |
\\ |
Backslash |
/ |
\/ |
Forward slash (optional) |
| Newline | \n |
Line feed |
| Tab | \t |
Horizontal tab |
| Carriage return | \r |
Carriage return |
| Unicode | \uXXXX |
Any Unicode character |
Beautify vs Minify: When to Use Each
Both beautified and minified JSON are equally valid — the difference is purely whitespace.
| Beautified | Minified | |
|---|---|---|
| Format | Indented, one value per line | Compact, no whitespace |
| Readability | ✅ Human-friendly | ❌ Machine-friendly only |
| File size | Larger | 20–40% smaller |
| Use case | Debugging, config files, code review, documentation | Production APIs, network payloads, storage |
| Parsing speed | Marginally slower | Marginally faster |
Beautified Example
{
"user": {
"id": 101,
"name": "Alice",
"roles": ["admin", "editor"],
"active": true
}
}
Minified Example
{"user":{"id":101,"name":"Alice","roles":["admin","editor"],"active":true}}
Rule of thumb: Always develop and debug with beautified JSON. Always deploy and transmit with minified JSON. Your bandwidth and your future self will both thank you.
How to Use a JSON Formatter
A good online JSON formatter does three things: validates, beautifies, and minifies — all in one step.
Step-by-Step Workflow
- Paste your raw JSON — from an API response, log file, config, or database export
- Click Validate — the tool checks syntax and highlights the exact line and character position of any error
- Fix errors — use the error message and this guide's error table to correct the issue
- Choose your output format:
- Beautify → indented, readable output for debugging or documentation
- Minify → compact output for production use
- Copy or download the result
What a Good JSON Formatter Should Do
| Feature | Why It Matters |
|---|---|
| Syntax error highlighting | Points to exact line/column of the problem |
| Tree view / collapsible nodes | Navigate large JSON structures without scrolling |
| Search within JSON | Find specific keys or values instantly |
| Type indicators | Shows whether a value is string, number, boolean, etc. |
| Copy to clipboard | One-click copy of formatted output |
| No data storage | Your JSON never leaves your browser |
JSON in 6 Programming Languages
JavaScript
// Parse JSON string → object
const obj = JSON.parse('{"name": "Alice", "age": 30}');
console.log(obj.name); // "Alice"
// Convert object → JSON string (beautified)
const json = JSON.stringify(obj, null, 2);
// Convert object → JSON string (minified)
const minified = JSON.stringify(obj);
// Handle parse errors safely
try {
const data = JSON.parse(rawString);
} catch (e) {
console.error("Invalid JSON:", e.message);
}
// Deep clone an object using JSON (quick trick)
const clone = JSON.parse(JSON.stringify(original));
Python
import json
# Parse JSON string → dict
obj = json.loads('{"name": "Alice", "age": 30}')
print(obj["name"]) # Alice
# Convert dict → JSON string (beautified)
json_str = json.dumps(obj, indent=2)
# Convert dict → JSON string (minified)
minified = json.dumps(obj, separators=(',', ':'))
# Read JSON from file
with open("data.json", "r") as f:
data = json.load(f)
# Write JSON to file (beautified)
with open("output.json", "w") as f:
json.dump(data, f, indent=2)
PHP
// Parse JSON string → associative array
$obj = json_decode('{"name": "Alice", "age": 30}', true);
echo $obj["name"]; // Alice
// Convert array → JSON string (beautified)
$json = json_encode($obj, JSON_PRETTY_PRINT);
// Convert array → JSON string (minified)
$minified = json_encode($obj);
// Check for errors
if (json_last_error() !== JSON_ERROR_NONE) {
echo "JSON Error: " . json_last_error_msg();
}
Java
// Using Jackson (most common library)
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
// Parse JSON string → object
MyClass obj = mapper.readValue(jsonString, MyClass.class);
// Parse JSON → generic Map
Map<String, Object> map = mapper.readValue(jsonString, Map.class);
// Convert object → JSON string (beautified)
String pretty = mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(obj);
// Convert object → JSON string (minified)
String minified = mapper.writeValueAsString(obj);
C# (.NET)
using System.Text.Json;
// Parse JSON string → object
var obj = JsonSerializer.Deserialize<MyClass>(jsonString);
// Convert object → JSON string (minified)
string json = JsonSerializer.Serialize(obj);
// Convert object → JSON string (beautified)
var options = new JsonSerializerOptions { WriteIndented = true };
string pretty = JsonSerializer.Serialize(obj, options);
// Parse to dynamic JsonDocument
using JsonDocument doc = JsonDocument.Parse(jsonString);
string name = doc.RootElement.GetProperty("name").GetString();
Go
import "encoding/json"
// Parse JSON → struct
var obj MyStruct
err := json.Unmarshal([]byte(jsonString), &obj)
// Parse JSON → generic map
var result map[string]interface{}
json.Unmarshal([]byte(jsonString), &result)
// Convert struct → JSON (minified)
data, err := json.Marshal(obj)
// Convert struct → JSON (beautified)
data, err := json.MarshalIndent(obj, "", " ")
JSONPath: Querying JSON Data
JSONPath is to JSON what XPath is to XML — a query language for extracting specific values from a JSON structure.
JSONPath Syntax
| Expression | Meaning |
|---|---|
$ |
Root element |
.key |
Child key |
..key |
Recursive descent (search all levels) |
[n] |
Array element at index n (0-based) |
[*] |
All array elements |
[start:end] |
Array slice |
[?(@.key == value)] |
Filter expression |
JSONPath Examples
Given this JSON:
{
"store": {
"books": [
{"title": "Clean Code", "price": 29.99, "inStock": true},
{"title": "The Pragmatic Programmer", "price": 34.99, "inStock": false},
{"title": "Refactoring", "price": 39.99, "inStock": true}
],
"name": "Dev Books"
}
}
| JSONPath Query | Result |
|---|---|
$.store.name |
"Dev Books" |
$.store.books[0].title |
"Clean Code" |
$.store.books[*].title |
All three titles |
$.store.books[?(@.inStock == true)].title |
"Clean Code", "Refactoring" |
$.store.books[?(@.price < 35)].title |
"Clean Code", "The Pragmatic Programmer" |
$..price |
All price values at any depth |
JSON Schema: Validating JSON Structure
JSON Schema lets you define the expected structure of a JSON document and validate any JSON against it — essential for API contracts and data pipelines.
Basic JSON Schema Example
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["name", "age", "email"],
"properties": {
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
},
"email": {
"type": "string",
"format": "email"
},
"roles": {
"type": "array",
"items": { "type": "string" },
"minItems": 1
}
},
"additionalProperties": false
}
JSON Schema Validation Keywords
| Keyword | Applies To | Purpose |
|---|---|---|
type |
All | Enforce data type |
required |
Object | List of mandatory keys |
properties |
Object | Define each property's schema |
additionalProperties |
Object | Allow/deny undeclared keys |
minLength / maxLength |
String | String length constraints |
pattern |
String | Regex validation |
minimum / maximum |
Number | Numeric range |
enum |
Any | Restrict to specific values |
items |
Array | Schema for array elements |
minItems / maxItems |
Array | Array length constraints |
JSON vs Related Formats
JSON is not always the right choice. Here's how it compares to common alternatives:
| Format | Human Readable | Comments | Types | Best For |
|---|---|---|---|---|
| JSON | ✅ Good | ❌ No | 6 types | APIs, web data exchange |
| YAML | ✅ Excellent | ✅ Yes | Rich | Config files, DevOps |
| TOML | ✅ Good | ✅ Yes | Rich | App config, Rust/Go projects |
| XML | ⚠️ Verbose | ✅ Yes | Strings | Enterprise, document markup |
| CSV | ✅ Simple | ❌ No | Strings | Tabular data, spreadsheets |
| MessagePack | ❌ Binary | ❌ No | JSON types | High-performance APIs |
| Protocol Buffers | ❌ Binary | ❌ No | Typed | gRPC, high-throughput systems |
When to choose JSON: Default choice for REST APIs, web storage, and any context where human readability and universal tooling support matter more than performance or schema strictness.
Frequently Asked Questions
Q: Why does my JSON look valid but still fails to parse? Check for: invisible Unicode characters (copy-paste from Word/PDF), a BOM (byte order mark) at the start of the file, or encoding issues (ensure UTF-8 without BOM). A JSON formatter will catch all of these.
Q: Can JSON have duplicate keys? Technically the JSON spec says behaviour is "undefined" for duplicate keys — it's not explicitly forbidden but not valid either. In practice, most parsers accept it but only keep the last value. Avoid duplicate keys entirely.
Q: What is the maximum size of a JSON file?
There is no size limit in the JSON specification. Practical limits are set by the parser, available memory, and network constraints. For very large datasets (100MB+), consider streaming parsers like json-stream (Node.js) or ijson (Python).
Q: Is JSON5 the same as JSON? No. JSON5 is a superset of JSON that adds comments, trailing commas, single quotes, and unquoted keys — making it more human-friendly. It is not valid JSON and requires a separate parser. It's popular for config files but not for APIs.
Q: How do I handle dates in JSON?
JSON has no native date type. The universal convention is ISO 8601 format: "2025-06-05T03:28:00Z". Always store dates as strings in this format and parse them in your application layer.
Quick Reference Summary
| Task | Tool / Syntax |
|---|---|
| Validate JSON | Online formatter or JSON.parse() in browser console |
| Beautify JSON | Online formatter, JSON.stringify(obj, null, 2) |
| Minify JSON | Online formatter, JSON.stringify(obj) |
| Parse in JS | JSON.parse(string) |
| Parse in Python | json.loads(string) |
| Parse in PHP | json_decode(string, true) |
| Query JSON | JSONPath expressions |
| Validate structure | JSON Schema |
| Check for errors | Look for: trailing commas, single quotes, unquoted keys, uppercase booleans |
Use our free JSON Formatter to validate, beautify, and minify any JSON instantly — paste your JSON and get a clean, error-free result in one click.
Try the Free Calculator
Put this guide into practice instantly with our free developer tools tools — no sign-up required.
Browse All Tools