JSON Syntax Guide: The Complete Reference for Developers
Meta Description: Master JSON syntax with this complete guide. Learn data types, nesting, arrays, objects, common errors, and best practices for writing valid JSON every time.
JSON (JavaScript Object Notation) is the lingua franca of modern web development. APIs speak it. Config files use it. Databases store it. If you write code in 2025, you work with JSON — probably every single day.
But here's the thing: JSON's simplicity is deceptive. The syntax has strict rules, and a single misplaced comma can break everything. No helpful error message. Just "invalid JSON" and twenty minutes of squinting at brackets.
This guide covers everything you need to know about JSON syntax — from the basics to the edge cases that trip up even experienced developers.
What is JSON?
JSON is a lightweight text-based data format. It was derived from JavaScript object syntax but is language-independent. Every major programming language can parse and generate JSON.
A simple JSON object:
{
"name": "Alice",
"age": 30,
"developer": true
}
That's it. Curly braces, key-value pairs, commas between them. The simplicity is the point — JSON is meant to be easy for both humans and machines to read.
The Six Data Types
JSON supports exactly six data types. No more, no less.
1. Strings
Strings are enclosed in double quotes. Not single quotes. Not backticks. Double quotes only.
{
"greeting": "Hello, World!",
"empty": "",
"unicode": "こんにちは"
}
Escape sequences:
\"— Double quote\\— Backslash\/— Forward slash (optional but valid)\n— Newline\t— Tab\r— Carriage return\b— Backspace\f— Form feed\uXXXX— Unicode character (e.g.,\u00E9for é)
Common mistake: Using single quotes.
// WRONG
{ 'name': 'Alice' }
// RIGHT
{ "name": "Alice" }
2. Numbers
Numbers can be integers or floating-point. No quotes around them.
{
"integer": 42,
"negative": -17,
"float": 3.14159,
"scientific": 2.998e8,
"negativeExponent": 1.6e-19
}
Rules:
- No leading zeros (except
0itself or0.x) - No hex, octal, or binary notation
- No
InfinityorNaN - No trailing decimal point (
1.is invalid, use1.0)
// WRONG
{ "value": 0xFF } // No hex
{ "value": 042 } // No octal
{ "value": NaN } // No NaN
{ "value": 1. } // No trailing dot
// RIGHT
{ "value": 255 }
{ "value": 42 }
{ "value": null } // Use null instead of NaN
{ "value": 1.0 }
3. Booleans
true or false. Lowercase. No quotes.
{
"active": true,
"deleted": false
}
Common mistake: Quoting booleans or using capitalized versions.
// WRONG
{ "active": "true" } // This is a string, not a boolean
{ "active": True } // Python-style, not valid JSON
{ "active": TRUE } // SQL-style, not valid JSON
4. Null
null represents the absence of a value. Lowercase. No quotes.
{
"middleName": null,
"deletedAt": null
}
Note: null, undefined, and missing keys are different concepts. JSON has null but does not have undefined. Omitting a key entirely is different from setting it to null.
5. Objects
Objects are unordered collections of key-value pairs enclosed in curly braces.
{
"user": {
"id": 1,
"name": "Alice",
"email": "[email protected]",
"address": {
"street": "123 Main St",
"city": "Springfield",
"country": "US"
}
}
}
Rules:
- Keys must be strings (double-quoted)
- Key-value pairs separated by commas
- No trailing commas
- Keys should be unique (duplicates are technically parsed but behavior is undefined)
6. Arrays
Arrays are ordered lists of values enclosed in square brackets.
{
"colors": ["red", "green", "blue"],
"matrix": [[1, 2], [3, 4], [5, 6]],
"mixed": [42, "hello", true, null, {"nested": "object"}]
}
Arrays can contain any JSON data type, including other arrays and objects. They can also mix types, though in practice you usually want consistent types.
Structure Rules
The Root Element
A valid JSON document must have exactly one root element — either an object or an array.
// Valid: object root
{ "key": "value" }
// Valid: array root
[1, 2, 3]
// Valid: single value (per RFC 8259)
"just a string"
42
true
null
Technically, RFC 8259 (the current JSON standard) allows any JSON value as a root element. But most APIs and applications expect an object or array at the root.
No Trailing Commas
This is probably the #1 source of JSON syntax errors. Unlike JavaScript, JSON does not allow trailing commas.
// WRONG - trailing comma after "blue"
{
"colors": ["red", "green", "blue",]
}
// WRONG - trailing comma after last property
{
"name": "Alice",
"age": 30,
}
// RIGHT
{
"colors": ["red", "green", "blue"],
"name": "Alice",
"age": 30
}
No Comments
JSON does not support comments. At all. This was a deliberate design decision by Douglas Crockford (JSON's creator) to keep the format simple and prevent abuse.
// WRONG - no comments allowed
{
"name": "Alice", // inline comment
/* block comment */
"age": 30
}
If you need comments in configuration files, consider:
- JSON5 — A superset that allows comments, trailing commas, and more
- JSONC — JSON with Comments (used by VS Code config files)
- YAML — An alternative format that supports comments
- Convention: Use a
"_comment"key (hacky but works)
Whitespace
Whitespace (spaces, tabs, newlines) between tokens is ignored. These are all equivalent:
{"name":"Alice","age":30}
{
"name": "Alice",
"age": 30
}
{
"name" : "Alice" ,
"age" : 30
}
Minified JSON (no whitespace) saves bytes for transmission. Pretty-printed JSON (with indentation) is easier for humans. Use the right format for the context.
Common Patterns
Nested Objects
Real-world JSON is often deeply nested:
{
"order": {
"id": "ORD-001",
"customer": {
"name": "Alice",
"address": {
"line1": "123 Main St",
"city": "Springfield",
"state": "IL",
"zip": "62701"
}
},
"items": [
{
"product": "Widget",
"quantity": 3,
"price": 9.99
},
{
"product": "Gadget",
"quantity": 1,
"price": 24.99
}
],
"total": 54.96
}
}
Arrays of Objects
The most common API response pattern:
{
"users": [
{ "id": 1, "name": "Alice", "role": "admin" },
{ "id": 2, "name": "Bob", "role": "user" },
{ "id": 3, "name": "Charlie", "role": "user" }
],
"total": 3,
"page": 1
}
Enums as Strings
JSON doesn't have an enum type. Use strings:
{
"status": "active",
"priority": "high",
"type": "subscription"
}
Dates
JSON doesn't have a date type. The most common convention is ISO 8601 strings:
{
"createdAt": "2025-01-15T10:30:00Z",
"updatedAt": "2025-01-15T14:22:33+05:30",
"date": "2025-01-15"
}
Some APIs use Unix timestamps instead:
{
"createdAt": 1736935800,
"createdAtMs": 1736935800000
}
Debugging Invalid JSON
When your JSON won't parse, here's a systematic approach:
-
Use a formatter. Paste your JSON into our JSON formatter to instantly see syntax errors with line numbers and descriptions.
-
Check for trailing commas. This is the most common issue, especially when copy-pasting or manually editing.
-
Check for single quotes. If you're coming from Python or JavaScript, you might habitually use single quotes.
-
Check for unescaped special characters. Newlines, tabs, and backslashes inside strings must be escaped.
-
Check for missing commas. Between key-value pairs and array elements.
-
Check for extra commas. After the last element in arrays or objects.
-
Validate programmatically:
# Command line echo '{"test": "value"}' | python -m json.tool
Or use jq
echo '{"test": "value"}' | jq .
## JSON vs Alternatives
| Feature | JSON | XML | YAML | TOML |
|---------|------|-----|------|------|
| Human readable | Good | Verbose | Best | Good |
| Comments | No | Yes | Yes | Yes |
| Data types | 6 | Text only | Rich | Rich |
| File size | Small | Large | Smaller | Small |
| Parsing speed | Fast | Slower | Slower | Fast |
| Trailing commas | No | N/A | N/A | Yes |
| Industry standard | APIs, configs | Legacy, SOAP | DevOps, configs | Rust/Go configs |
JSON wins in APIs and data exchange because it's simple, fast to parse, and universally supported. It loses in configuration files where comments and flexibility matter more.
## Best Practices
1. **Use consistent key naming.** Pick `camelCase`, `snake_case`, or `kebab-case` and stick with it throughout your API.
2. **Keep nesting reasonable.** If you're more than 4-5 levels deep, consider flattening your structure.
3. **Use meaningful key names.** `"usr_nm"` saves three characters and costs hours of confusion.
4. **Prefer objects over positional arrays.** `{"lat": 40.7, "lng": -74.0}` is clearer than `[40.7, -74.0]`.
5. **Handle large numbers carefully.** JavaScript's `Number.MAX_SAFE_INTEGER` is 2^53. If your IDs exceed this, send them as strings.
6. **Use `null` intentionally.** There's a difference between "this field exists but has no value" (`null`) and "this field doesn't exist" (omitted).
7. **Validate with JSON Schema.** For APIs, define your expected structure with JSON Schema and validate incoming data automatically.
---
## FAQ
### Why doesn't JSON support comments?
Douglas Crockford deliberately excluded comments to keep JSON simple and prevent people from using them for parsing directives, which would create interoperability issues. For config files where comments matter, use JSON5, JSONC, or YAML instead.
### What's the maximum size of a JSON document?
The JSON spec doesn't define a maximum size. Limits are imposed by parsers, frameworks, and transport layers. Most web servers default to 1-10MB request body limits. Browsers can handle JSON documents of hundreds of megabytes, though performance degrades.
### Can JSON keys contain special characters?
Yes — JSON keys are strings, so they can contain any valid Unicode character, including spaces, dots, and special symbols. However, keys with special characters are harder to access in most programming languages, so simple alphanumeric names are recommended.
### Is JSON faster than XML?
Generally yes. JSON is more compact (less markup overhead) and faster to parse in most languages. Benchmarks typically show JSON parsing at 2-10x faster than XML, depending on the parser and data structure.
### How do I handle circular references in JSON?
You can't. JSON doesn't support references — it's a tree structure, not a graph. If your data has circular references, you need to break the cycle (e.g., replace one reference with an ID) before serializing to JSON.