JavaScript JSON and Data Fetching
(Working with data using JSON and fetch API)
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data format used for storing and transporting data, especially between a server and a web application.
JSON Syntax Rules:
- Data is in
key/value pairs
- Keys and string values are enclosed in
double quotes
- Can hold objects, arrays, strings, numbers, booleans, and null
Example:
{
"name": "John",
"age": 30,
"isStudent": false,
"hobbies": ["coding", "music"]
}
Converting Between JSON and JavaScript
JSON ➡️ JavaScript (Parsing)
const jsonString = '{"name": "Alice", "age": 25}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // Alice
JavaScript ➡️ JSON (Stringifying)
const user = { name: "Bob", age: 40 };
const json = JSON.stringify(user);
console.log(json); // {"name":"Bob","age":40}
The Fetch API
The fetch()
function is used to make network requests (GET, POST, etc.) and receive data—often in JSON format.
Basic Fetch Example (GET request)
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
Using async/await with Fetch
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();
Making a POST Request with Fetch
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));
Common JSON Mistakes
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 |
Summary
- JSON is the standard format for data exchange on the web.
- Use
JSON.parse()
to convert JSON to objects andJSON.stringify()
for the reverse. - Use the
fetch()
API to get/post data from servers. - Always handle errors to ensure your app is stable.
🧪 Practice Exercise:
Task:
- Convert a JSON string to a JS object and access its properties.
- Convert a JS object to a JSON string and log it.
- Use
fetch()
to get a list of posts from a dummy API and display them. - Post a new record using fetch() and JSON.stringify().
- Handle errors using
.catch()
ortry...catch
.