JavaScript — Lesson 10
JSON & Fetch API
Working with data formats and making HTTP requests.
JSON & Fetch API
JSON is the standard data format for web APIs. The Fetch API lets you send and receive data from servers.
JSON Basics
const user = { name: "Alice", age: 25 };
// Convert to JSON string
const json = JSON.stringify(user);
// '{"name":"Alice","age":25}'
// Parse JSON string back to object
const parsed = JSON.parse(json);
console.log(parsed.name); // "Alice"
The Fetch API
// GET request with promises
fetch("https://api.example.com/users")
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
Async/Await
A cleaner syntax for working with Promises.
async function getUsers() {
try {
const res = await fetch("/api/users");
const data = await res.json();
console.log(data);
} catch (err) {
console.error("Failed:", err);
}
}
POST Request
async function createUser(name, email) {
const res = await fetch("/api/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name, email })
});
return res.json();
}
Checking Response Status
const res = await fetch("/api/data");
if (!res.ok) {
throw new Error(`HTTP error: ${res.status}`);
}
const data = await res.json();
Displaying Fetched Data
<div id="users">Loading...</div>
<script>
async function loadUsers() {
try {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
const users = await res.json();
const html = users.map(u =>
"<div style='margin:8px;padding:12px;background:#f0f0f0;border-radius:6px;'>" +
"<strong>" + u.name + "</strong><br>" + u.email +
"</div>"
).join("");
document.getElementById("users").innerHTML = html;
} catch (err) {
document.getElementById("users").textContent = "Error loading data.";
}
}
loadUsers();
</script>
Tip: Always use
try/catch with fetch. Network requests can fail for many reasons - no internet, server down, invalid URL, or CORS errors.
Practice what you learned in the Deoit Editor — a free, browser-based code editor.
Open Editor →