Skip to main content

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

TypeExample
String"hello"
Number42, 3.14, -17
Booleantrue, false
Nullnull
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

FormatBest For
JSONAPIs, config, general interchange
CSVTabular data, spreadsheet import
YAMLHuman-edited configuration
XMLLegacy systems, SOAP
ParquetAnalytics, columnar queries
MessagePackBinary 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

  1. Validate input: Never trust external JSON (use Zod, Joi, ajv)
  2. Use ISO 8601 for dates: "2024-01-15T10:30:00Z"
  3. Keep it flat: Deep nesting complicates parsing
  4. Consider JSON:API: Standard for API responses
  5. Compress for transfer: gzip significantly reduces size
  • JSONPath: Query JSON like XPath queries XML
  • jq: Command-line JSON processor
  • JSON Schema: Formal schema definition
  • JSON5: JSON with comments and trailing commas