JSON (JavaScript Object Notation) has become the lingua franca of web development. APIs speak it, configuration files use it, and databases store it. Here's everything you need to know about JSON.
What is JSON?
JSON is a lightweight, text-based data interchange format. Despite "JavaScript" in the name, it's language-independent and supported by virtually every programming language.
A simple JSON example:
{
"name": "Alice",
"age": 30,
"isStudent": false,
"courses": ["Math", "Science"],
"address": {
"city": "New York",
"zip": "10001"
}
}
JSON was created by Douglas Crockford in the early 2000s as a simpler alternative to XML. Its similarity to JavaScript object literals made it natural for web applications.
JSON Syntax Rules
JSON has strict syntax rules—stricter than JavaScript:
1. Data is in key-value pairs
"key": "value"
2. Keys must be strings in double quotes
{"name": "Alice"} ✓ Valid
{name: "Alice"} ✗ Invalid (unquoted key)
{'name': 'Alice'} ✗ Invalid (single quotes)
3. Values must be valid JSON types
- Strings (double quotes only)
- Numbers
- Booleans (
trueorfalse) null- Arrays
- Objects
4. No trailing commas
{"a": 1, "b": 2,} ✗ Invalid
{"a": 1, "b": 2} ✓ Valid
5. No comments
JSON does not support comments. This is intentional—JSON is for data, not documentation.
{
"name": "Alice" // This is NOT allowed
}
JSON Data Types
Strings
Must use double quotes. Escape special characters:
{
"simple": "Hello",
"with_quotes": "She said \"Hello\"",
"newline": "Line 1\nLine 2",
"unicode": "Emoji: \u263A"
}
Escape sequences: \" \\ \/ \b \f \n \r \t \uXXXX
Numbers
No quotes. Supports integers, decimals, and scientific notation:
{
"integer": 42,
"negative": -17,
"decimal": 3.14159,
"scientific": 1.23e10
}
Note: No hex (0xFF), octal (077), or leading zeros (007).
Booleans
Lowercase only:
{
"active": true,
"deleted": false
}
Null
Represents "no value":
{
"middleName": null
}
Arrays
Ordered lists in square brackets:
{
"numbers": [1, 2, 3],
"mixed": [1, "two", true, null],
"nested": [[1, 2], [3, 4]]
}
Objects
Key-value pairs in curly braces:
{
"person": {
"name": "Bob",
"age": 25
}
}
Objects vs Arrays
Use objects for named properties:
{
"name": "Product",
"price": 29.99,
"inStock": true
}
Use arrays for ordered collections:
{
"tags": ["electronics", "sale", "featured"]
}
Common pattern—array of objects:
{
"users": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
]
}
Nested Structures
JSON can be deeply nested:
{
"company": {
"name": "Tech Corp",
"departments": [
{
"name": "Engineering",
"employees": [
{"name": "Alice", "skills": ["Python", "JavaScript"]},
{"name": "Bob", "skills": ["Java", "Go"]}
]
}
]
}
}
Accessing nested values (JavaScript):
data.company.departments[0].employees[1].name // "Bob"
Common JSON Errors and How to Fix Them
1. Single quotes instead of double
{'name': 'Alice'} ✗ Use double quotes
{"name": "Alice"} ✓
2. Trailing comma
{"a": 1, "b": 2,} ✗ Remove trailing comma
{"a": 1, "b": 2} ✓
3. Unquoted keys
{name: "Alice"} ✗ Quote the key
{"name": "Alice"} ✓
4. Comments
{
"name": "Alice" // comment ✗ Remove comments
}
5. Invalid escape sequences
{"path": "C:\Users\name"} ✗ Backslash needs escaping
{"path": "C:\\Users\\name"} ✓
6. Control characters in strings
Newlines and tabs must be escaped:
{"text": "line1
line2"} ✗
{"text": "line1\nline2"} ✓
JSON vs XML Comparison
| Feature | JSON | XML |
|---|---|---|
| Syntax | {"key": "value"} |
<key>value</key> |
| Verbosity | Compact | More verbose |
| Data types | Yes (number, boolean, null) | All values are text |
| Arrays | Native support | Need conventions |
| Comments | Not supported | Supported |
| Attributes | No | Yes |
| Namespaces | No | Yes |
| Schema | JSON Schema | XSD, DTD |
| Parsing | Fast, built-in in browsers | Slower |
JSON won for APIs because it's simpler and lighter. XML is still used where its features (comments, namespaces, attributes) are valuable.
JSON in APIs
REST APIs typically exchange JSON:
Request:
POST /api/users HTTP/1.1
Content-Type: application/json
{"name": "Alice", "email": "alice@example.com"}
Response:
HTTP/1.1 201 Created
Content-Type: application/json
{"id": 123, "name": "Alice", "email": "alice@example.com", "createdAt": "2024-01-15T10:30:00Z"}
Pretty Printing vs Minified
Pretty printed (readable):
{
"name": "Alice",
"age": 30
}
Minified (compact, for transmission):
{"name":"Alice","age":30}
Minification removes whitespace to reduce file size. Always pretty print for debugging.
JSON Schema Basics
JSON Schema validates JSON structure:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0},
"email": {"type": "string", "format": "email"}
},
"required": ["name", "email"]
}
This schema ensures:
nameis a required stringageis a non-negative integer (if present)emailis a required string in email format
Working with JSON in Code
JavaScript
// Parse JSON string to object
const obj = JSON.parse('{"name": "Alice"}');
// Convert object to JSON string
const json = JSON.stringify({name: "Alice"}, null, 2);
Python
import json
# Parse JSON
obj = json.loads('{"name": "Alice"}')
# Create JSON
json_string = json.dumps({"name": "Alice"}, indent=2)
Handling Errors
try {
const data = JSON.parse(userInput);
} catch (e) {
console.error("Invalid JSON:", e.message);
}
Summary
JSON's simplicity made it the standard for data interchange:
- Key-value pairs with strict syntax
- Six data types: string, number, boolean, null, array, object
- No comments or trailing commas
- Language-independent but JavaScript-friendly
- Perfect for APIs and configuration
Master JSON and you'll work smoothly with web APIs, configuration files, and data storage.
Need to format or validate JSON? Try our JSON Formatter tool!