JSON
JSON (JavaScript Object Notation) is a lightweight data interchange format that has become the de facto standard for web APIs and configuration files. Its simplicity and language independence make it ubiquitous in modern software.
Format
{
"name": "Alice",
"age": 30,
"email": "alice@example.com",
"roles": ["admin", "user"],
"address": {
"city": "Sydney",
"country": "Australia"
},
"active": true,
"metadata": null
}
Data Types
| Type | Example |
|---|---|
| String | "hello" |
| Number | 42, 3.14, -17 |
| Boolean | true, false |
| Null | null |
| Array | [1, 2, 3] |
| Object | {"key": "value"} |
Common Operations
JavaScript
// Parse JSON string
const data = JSON.parse('{"name": "Alice"}');
// Stringify object
const json = JSON.stringify({ name: 'Alice' }, null, 2);
// Fetch API returns JSON
const response = await fetch('/api/users');
const users = await response.json();
Schema Validation
// Using Zod
import { z } from 'zod';
const UserSchema = z.object({
name: z.string(),
email: z.string().email(),
age: z.number().optional(),
});
const user = UserSchema.parse(jsonData);
JSON vs Alternatives
| Format | Best For |
|---|---|
| JSON | APIs, config, general interchange |
| CSV | Tabular data, spreadsheet import |
| YAML | Human-edited configuration |
| XML | Legacy systems, SOAP |
| Parquet | Analytics, columnar queries |
| MessagePack | Binary JSON, performance |
What We Like
- Simplicity: Easy to read, write, and understand
- Universal: Every language has JSON support
- Web native: JavaScript parses it natively
- Self-describing: Schema is implicit in structure
- Tooling: Excellent editor and debugger support
What We Don't Like
- No comments: Unlike YAML or JSON5
- Verbosity: Repeated keys, lots of quotes
- No dates: Must use strings or numbers
- Limited types: No distinction between int/float
- Large files: Less efficient than binary formats
Best Practices
- Validate input: Never trust external JSON (use Zod, Joi, ajv)
- Use ISO 8601 for dates:
"2024-01-15T10:30:00Z" - Keep it flat: Deep nesting complicates parsing
- Consider JSON:API: Standard for API responses
- Compress for transfer: gzip significantly reduces size
Related Tools
- JSONPath: Query JSON like XPath queries XML
- jq: Command-line JSON processor
- JSON Schema: Formal schema definition
- JSON5: JSON with comments and trailing commas