JavaScript JSON

JavaScript JSON (JavaScript Object Notation)
JSON (JavaScript Object Notation) is a lightweight data format used for storing and transferring data between a server and a web application. It is easy for humans to read and easy for machines to parse.
Why JSON?
Language-independent (supported in almost all programming languages)
Commonly used in APIs and data exchange
Easy to read and write
Works perfectly with JavaScript objects
JSON Syntax Rules
| Rule | Example |
|---|---|
| Data is written in key/value pairs | "name": "John" |
| Keys must be strings with double quotes | "age" |
| Values can be string, number, boolean, null, array, or object | "active": true |
Object is wrapped {} | { "name": "John" } |
Array is wrapped [] | [ "apple", "orange" ] |
Example JSON Object
JSON vs JavaScript Object
| Feature | JavaScript Object | JSON |
|---|---|---|
| Keys | No quotes needed | Must use double quotes |
| Comments | Allowed | Not allowed |
| Functions | Allowed | Not allowed |
Example difference:
Convert JSON to Js Object
1 2 3 4 5 6 7 8 9 10 | Using JSON.parse(): let jsonText = '{ "name": "John", "age": 30 }'; let obj = JSON.parse(jsonText); console.log(obj.name); // Output: John |
Convert Js Object to JSON
1 2 3 4 5 6 7 8 9 10 11 | Using JSON.stringify(): let obj = { name: "John", age: 30 }; let json = JSON.stringify(obj); console.log(json); // Output: {"name":"John","age":30} |
JSON with Arrays
Unsupported Values in JSON
| Unsupported | Reason |
|---|---|
| Functions | Not serializable |
undefined | JSON cannot store it |
| Date object (becomes string) | Requires conversion |
Example Date handling:
JSON with Fetch API Example (Real Use Case)
Pretty Formatting JSON
Summary
| Concept | Method |
|---|---|
| Parse JSON → Object | JSON.parse() |
| Convert Object → JSON | JSON.stringify() |
| Indent JSON | JSON.stringify(obj, null, spacing) |
| Data Exchange format | API, localStorage, server |
