What is JSON?
JSON (JavaScript Object Notation) is a lightweight, text-based data format used for storing and exchanging data. It's the most popular format for APIs and configuration files due to its simplicity and universal support across programming languages.
JSON Syntax
JSON syntax is derived from JavaScript object notation, but it's stricter. Here are the key rules:
- Data is in key/value pairs
- Keys must be strings in double quotes
- Data is separated by commas
- Curly braces hold objects
- Square brackets hold arrays
Basic JSON Example
{
"name": "John Doe",
"age": 30,
"email": "john@example.com",
"isActive": true,
"address": {
"city": "New York",
"country": "USA"
},
"hobbies": ["reading", "gaming", "hiking"]
}JSON Data Types
JSON supports six data types:
| Type | Description | Example |
|---|---|---|
| String | Text in double quotes | "Hello World" |
| Number | Integer or floating-point | 42, 3.14, -17 |
| Boolean | true or false | true, false |
| Null | Empty value | null |
| Object | Key-value pairs in curly braces | {"key": "value"} |
| Array | Ordered list in square brackets | [1, 2, 3] |
Common JSON Use Cases
1. REST APIs
JSON is the standard format for REST API responses. When you fetch data from a web service, it typically returns JSON:
// API Response
{
"status": "success",
"data": {
"users": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
]
}
}2. Configuration Files
Many applications use JSON for configuration, like package.json in Node.js or tsconfig.json in TypeScript:
{
"name": "my-project",
"version": "1.0.0",
"dependencies": {
"react": "^18.2.0",
"next": "^14.0.0"
}
}3. Data Storage
NoSQL databases like MongoDB store data in JSON-like documents, and localStorage in browsers uses JSON for storing complex data.
JSON Best Practices
- Always use double quotes for strings and keys (single quotes are invalid)
- No trailing commas after the last item in objects or arrays
- No comments - JSON doesn't support comments (use JSON5 or YAML if you need them)
- Use consistent indentation for readability (2 or 4 spaces)
- Validate your JSON before using it in production
Common JSON Errors
{'name': 'John'}Single quotes are invalid - use double quotes
{"items": [1, 2, 3,]}Trailing commas are not allowed
{name: "John"}Keys must be quoted strings
JSON vs Other Formats
| Feature | JSON | XML | YAML |
|---|---|---|---|
| Readability | Good | Moderate | Excellent |
| File Size | Compact | Verbose | Compact |
| Comments | No | Yes | Yes |
| Schema Support | JSON Schema | XSD, DTD | Limited |
Learn more about these formats: