## What Is JSON?
**JSON** (JavaScript Object Notation) is a lightweight, human-readable data interchange format. Standardized in RFC 8259 (2017), it's the de facto format for web APIs, configuration files, and semi-structured data.
## JSON Data Types
```json
{
"text": "Hello world",
"integer": 42,
"decimal": 3.14,
"boolean": true,
"null_value": null,
"array": [1, 2, 3, "four"],
"nested": {"name": "Alice", "age": 30},
"records": [
{"id": 1, "price": 1.20},
{"id": 2, "price": 0.80}
]
}
```
**Rules:** keys in double quotes, no comments, no trailing commas.
## JSON vs XML vs YAML
| Feature | JSON | XML | YAML |
|---------|------|-----|------|
| Readability | Good | Fair | Excellent |
| Verbosity | Low | High | Very low |
| Comments | ❌ | ✅ | ✅ |
| Schema | JSON Schema | XSD | ❌ |
| REST APIs | ✅ Standard | Legacy | Rare |
## JSON in Python
```python
import json
# Parse
data = json.loads('{"name": "Alice", "age": 28}')
print(data["name"])
# Serialize
person = {"name": "Bob", "hobbies": ["soccer", "reading"]}
json_str = json.dumps(person, ensure_ascii=False, indent=2)
# File I/O
with open("data.json", "r") as f:
data = json.load(f)
with open("output.json", "w") as f:
json.dump(person, f, ensure_ascii=False, indent=2)
# Minify
minified = json.dumps(person, separators=(",", ":"))
```
## JSON in JavaScript
```javascript
const data = JSON.parse('{"name":"Alice","age":28}');
const jsonStr = JSON.stringify({ name: "Bob" }, null, 2);
async function postData(url, payload) {
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
return response.json();
}
```
## JSON Schema Validation
```json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["name", "email"],
"properties": {
"name": {"type": "string", "minLength": 2},
"email": {"type": "string", "format": "email"},
"role": {"type": "string", "enum": ["admin", "user"]}
}
}
```
```python
import jsonschema
schema = {"type": "object", "required": ["name"],
"properties": {"name": {"type": "string"}}}
try:
jsonschema.validate({"name": "Alice"}, schema)
print("Valid JSON")
except jsonschema.ValidationError as e:
print(f"Error: {e.message}")
```
## CLI Tools (jq)
```bash
sudo apt install jq
cat data.json | jq . # Prettify
cat data.json | jq '.name' # Extract field
cat users.json | jq '.[] | select(.active == true)' # Filter
cat data.json | jq 'length' # Count
cat data.json | jq -c . # Minify
```
## JSON to CSV
```python
import json, csv
with open("users.json") as f:
data = json.load(f)
with open("users.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=data[0].keys())
writer.writeheader()
writer.writerows(data)
```
## Conclusion
**JSON is the dominant data interchange format** for web APIs, configurations, and semi-structured data. Its simplicity and universal support make it irreplaceable in modern web development.
Guide