Js Json in JavaScript
? JavaScript JSON (JavaScript Object Notation)
JSON is a lightweight data format used to store and exchange data. It is easy for humans to read and write, and easy for machines to parse and generate.
? What is JSON?
Stands for JavaScript Object Notation
Based on JavaScript object syntax
Used widely in APIs, config files, and data storage
Supports data types like string, number, object, array, boolean, null
? JSON vs JavaScript Object
// JavaScript Objectlet obj = { name: "Alice", age: 25 };// JSON stringlet jsonStr = '{"name": "Alice", "age": 25}';Differences:
JSON keys and string values must be in double quotes
JSON is purely a data format — it doesn't support methods or comments
? Converting Between JSON and JavaScript
? JSON.stringify(): Object ? JSON string
let person = { name: "Bob", age: 30 };let json = JSON.stringify(person);console.log(json); // '{"name":"Bob","age":30}'? JSON.parse(): JSON string ? Object
let jsonStr = '{"name":"Bob","age":30}';let obj = JSON.parse(jsonStr);console.log(obj.name); // Bob? Example with Fetch API (Real Use Case)
fetch("https://api.example.com/user") .then(response => response.json()) .then(data => { console.log(data.name); // Access JSON response as JS object });? JSON Format Example
{ "employees": [ { "name": "Alice", "age": 30 }, { "name": "Bob", "age": 25 } ]}? Invalid JSON Examples
Single quotes (must use
")Trailing commas
Comments (JSON doesn’t allow them)
?? Summary of JSON Methods
| Method | Description |
|---|---|
JSON.stringify() | Converts object to JSON string |
JSON.parse() | Converts JSON string to JS object |
Would you like to try a small project using JSON (e.g., loading data from a file or API)?