(Working with data using JSON and fetch API)
JSON (JavaScript Object Notation) is a lightweight data format used for storing and transporting data, especially between a server and a web application.
key/value pairsdouble quotes{
"name": "John",
"age": 30,
"isStudent": false,
"hobbies": ["coding", "music"]
}const jsonString = '{"name": "Alice", "age": 25}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // Aliceconst user = { name: "Bob", age: 40 };
const json = JSON.stringify(user);
console.log(json); // {"name":"Bob","age":40}The fetch() function is used to make network requests (GET, POST, etc.) and receive data—often in JSON format.
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));async function getUser() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Failed to fetch:", error);
}
}
getUser();const newUser = {
name: "Charlie",
email: "charlie@example.com"
};
fetch("https://jsonplaceholder.typicode.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(newUser)
})
.then(res => res.json())
.then(data => console.log("User added:", data))
.catch(err => console.error(err));| Mistake | Explanation |
|---|---|
| Using single quotes | JSON requires double quotes |
| Trailing commas | Not allowed in JSON |
| Undefined values | JSON does not support undefined |
| Circular references | JSON.stringify() fails on circular data |
JSON.parse() to convert JSON to objects and JSON.stringify() for the reverse.fetch() API to get/post data from servers.fetch() to get a list of posts from a dummy API and display them..catch() or try...catch.