📋 JSON = Universal Data Format
XML is heavy. JSON is lightweight. Human-readable, machine-parsable. Universal data exchange.
❌ XML (Heavy)
<user>
<name>Alice</name>
<age>30</age>
<email>alice@example.com</email>
</user>
✅ JSON (Lightweight)
{
"name": "Alice",
"age": 30,
"email": "alice@example.com"
}
📝 JSON Data Types
{
// String
"name": "John Doe",
// Number
"age": 30,
"price": 99.99,
// Boolean
"isActive": true,
"isAdmin": false,
// Null
"middleName": null,
// Array
"hobbies": ["reading", "gaming", "hiking"],
// Object (nested)
"address": {
"street": "123 Main St",
"city": "New York",
"zip": "10001"
},
// Array of objects
"orders": [
{
"id": 1,
"total": 150.00,
"items": ["item1", "item2"]
},
{
"id": 2,
"total": 75.50,
"items": ["item3"]
}
]
}
🎯 Working with JSON
// JavaScript
const user = {
name: 'Alice',
age: 30,
email: 'alice@example.com'
};
// Convert to JSON string
const jsonString = JSON.stringify(user);
console.log(jsonString);
// {"name":"Alice","age":30,"email":"alice@example.com"}
// Parse JSON string
const jsonData = '{"name":"Bob","age":25}';
const parsedUser = JSON.parse(jsonData);
console.log(parsedUser.name); // Bob
// Pretty print
const pretty = JSON.stringify(user, null, 2);
console.log(pretty);
// {
// "name": "Alice",
// "age": 30,
// "email": "alice@example.com"
// }
// With replacer (filter)
const filtered = JSON.stringify(user, ['name', 'age']);
console.log(filtered); // {"name":"Alice","age":30}
// With reviver (transform)
const dateData = '{"createdAt":"2024-01-15T10:00:00Z"}';
const parsed = JSON.parse(dateData, (key, value) => {
if (key === 'createdAt') {
return new Date(value);
}
return value;
});
// Validate JSON (try-catch)
try {
const data = JSON.parse(invalidJson);
} catch (error) {
console.error('Invalid JSON:', error);
}
💡 JSON Tips
- Always use double quotes
- No trailing commas
- Keys must be strings
- Use JSONLint to validate
- JSON is language-independent
“JSON is the universal data format. Lightweight, readable, everywhere. Essential for web development.”
