JSON
JSON = JavaScript Object Notation for data exchange
JSON Syntax
Similar to JavaScript objects
{
"name": "John",
"age": 30,
"isActive": true,
"hobbies": ["reading", "coding"],
"address": {
"city": "New York",
"country": "USA"
}
}
JSON vs JavaScript Objects
JSON = subset, stricter rules
| Feature | JSON | JavaScript |
|---|---|---|
| Keys | Must be strings | Can be identifiers |
| Quotes | Double quotes only | Single or double |
| Values | Limited types | Any JavaScript value |
| Comments | Not allowed | Allowed |
| Functions | Not allowed | Allowed |
JSON.parse()
Convert JSON string to object
const jsonString = '{"name":"John","age":30}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // "John"
"JSON.parse converts a JSON string into a JavaScript object."
JSON.stringify()
Convert object to JSON string
const obj = { name: "John", age: 30 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // '{"name":"John","age":30}'
"JSON.stringify converts a JavaScript object into a JSON string."
Supported Data Types
Primitives + objects + arrays
JSON supports:
- Strings
- Numbers
- Booleans
- null
- Objects
- Arrays
Not supported:
- Functions
- undefined
- Symbols
- Dates (become strings)
"JSON supports primitives, objects, and arrays, but not functions, undefined, symbols, or Date objects."
Common Use Cases
API communication · Storage · Configuration
- API requests/responses: Data exchange
- localStorage: Store data as JSON
- Configuration files: JSON configs
- Data serialization: Convert objects to strings
Replacer Function
Filter properties in stringify
const obj = { name: "John", age: 30, password: "secret" };
const json = JSON.stringify(obj, (key, value) => {
if (key === "password") return undefined; // Exclude
return value;
});
"JSON.stringify accepts a replacer function to filter or transform properties during serialization."
Reviver Function
Transform values in parse
const json = '{"date":"2023-01-01"}';
const obj = JSON.parse(json, (key, value) => {
if (key === "date") return new Date(value);
return value;
});
"JSON.parse accepts a reviver function to transform values during parsing."
Error Handling
Try-catch for invalid JSON
try {
const obj = JSON.parse(invalidJson);
} catch (error) {
console.error("Invalid JSON:", error);
}
"Always use try-catch when parsing JSON, as invalid JSON throws errors."
"JSON is a data format based on JavaScript objects, used for data exchange. It has stricter rules - double-quoted keys, no functions or comments. JSON.parse converts strings to objects, JSON.stringify converts objects to strings. JSON supports primitives, objects, and arrays. Use replacer/reviver functions for transformation. Always handle parsing errors."
🧠 Ultra-Short Cheat Sheet
Data interchange format
JSON.parse (string → object)
JSON.stringify (object → string)
Stricter than JavaScript
No functions, undefined, dates
API communication
localStorage
Error handling