JSON (JavaScript Object Notation) is a lightweight data format used to store and exchange data. It's human-readable, easy to parse, and has become the standard for web APIs and configuration files.
JSON Syntax
JSON uses key-value pairs:
{
"name": "John Doe",
"age": 30,
"email": "[email protected]",
"isActive": true,
"tags": ["developer", "designer"],
"address": {
"city": "Phoenix",
"state": "AZ"
}
}
JSON Data Types
- String: "Hello world" (in quotes)
- Number: 42, 3.14 (no quotes)
- Boolean: true, false
- Array: ["a", "b", "c"]
- Object: {"key": "value"}
- null: null
JSON vs. XML
| JSON | XML | |------|-----| | Less verbose | More verbose | | Easy to read | More complex | | Native to JavaScript | Requires parsing | | No comments | Supports comments | | Most APIs use it | Legacy systems |
Example in both:
JSON:
{"name": "John", "age": 30}
XML:
<person>
<name>John</name>
<age>30</age>
</person>
Common Uses
APIs
Most web APIs send and receive JSON:
GET /api/users/123
Response: {"id": 123, "name": "John", "email": "[email protected]"}
Configuration Files
package.json, tsconfig.json, etc.
Data Storage
NoSQL databases like MongoDB store JSON-like documents.
Data Exchange
Between frontend and backend, between services.
Working with JSON
JavaScript
// Parse JSON string to object
const data = JSON.parse('{"name": "John"}');
// Convert object to JSON string
const json = JSON.stringify({name: "John"});
Validation
Use JSON Schema to validate structure:
{
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number"}
},
"required": ["name"]
}
JSON Best Practices
- Use meaningful key names
- Keep nesting shallow when possible
- Use arrays for lists of similar items
- Validate against a schema for important data
- Use camelCase or snake_case consistently
- Handle parsing errors gracefully