About Lesson
Key Methods of JavaScript JSON:
1. JSON.stringify():
Converts a JavaScript object to a JSON string.
Example:
JavaScript
const person = { name: "Alice", age: 25 };
const jsonString = JSON.stringify(person);
console.log(jsonString); // Output: {"name":"Alice","age":25}
2. JSON.parse():
Converts a JSON string back into a JavaScript object.
Example:
JavaScript
const jsonString = '{"name":"Alice","age":25}';
const parsedObject = JSON.parse(jsonString);
console.log(parsedObject.name); // Output: Alice
Real-Life Use Case:
JSON is commonly used in web applications for server-client communication.
Example: Fetching data from an API
JavaScript
fetch("https://api.example.com/user")
.then(response => response.json())
.then(data => console.log(data));