CPCODELAB
JavaScript

fetch and JSON

11 min read

The Fetch API

fetch is the modern way to make HTTP requests from the browser (and Node.js 18+). It returns a Promise that resolves with a Response object.

javascript
// GET request
async function getPost(id) {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts/" + id);
  if (!res.ok) throw new Error("HTTP " + res.status);
  return res.json(); // parses body as JSON
}

// POST request with JSON body
async function createPost(post) {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(post)
  });
  return res.json();
}

await createPost({ title: "Hello", body: "World", userId: 1 });

JSON.parse and JSON.stringify

javascript
// JavaScript object → JSON string
const obj = { name: "Alice", scores: [95, 87] };
const json = JSON.stringify(obj);
// '{"name":"Alice","scores":[95,87]}'

// Pretty-print with indentation
JSON.stringify(obj, null, 2);

// JSON string → JavaScript object
const parsed = JSON.parse(json);
parsed.name; // "Alice"

// Handle parse errors
try {
  JSON.parse("not valid json");
} catch (e) {
  console.error("Bad JSON:", e.message);
}

JSON only supports strings, numbers, booleans, null, arrays, and plain objects. undefined, functions, and Symbols are silently dropped. Date objects become strings — parse them back after JSON.parse.

Ready to test yourself?
Practice JavaScript— quiz & coding exercises