Working with API-like Data
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — What a Server Actually Sends
When your game asks a server for a player's profile, the server answers with a single JSON string that packs everything together: a status, the trainer's info, and the full team of Codémon. Before you do anything with it, that response is still just one long `string`:
const response = '{"status":"ok","trainer":{"name":"Sam","badges":3},"team":[{"name":"Zap","type":"electric","level":4,"hp":45},{"name":"Aquachu","type":"water","level":12,"hp":0}]}';
console.log(typeof response);
console.log(response.length + " characters");Working with a server response always follows the same three steps: 1. Parse the JSON string into a real JavaScript object using `JSON.parse()`. 2. Check that the response succeeded (for example, `data.status === "ok"`). 3. Navigate into the nested objects and arrays to read what you need.
const response = '{"status":"ok","trainer":{"name":"Sam","badges":3},"team":[{"name":"Zap","type":"electric","level":4,"hp":45},{"name":"Aquachu","type":"water","level":12,"hp":0}]}';
const data = JSON.parse(response);
console.log(data.status);
console.log(data.trainer.name);Exercise 2 — Navigating the Shape
Once `JSON.parse()` rebuilds the response into `data`, you are working with ordinary nested JavaScript objects and arrays. To reach any value inside, follow the path from left to right, one step at a time: 1. `data.team` reaches the array of Codémon. 2. `data.team[0]` selects the first Codémon object in that array. 3. `data.team[0].name` reads that Codémon's `name` property.
const data = JSON.parse('{"status":"ok","trainer":{"name":"Sam","badges":3},"team":[{"name":"Zap","type":"electric","level":4,"hp":45},{"name":"Aquachu","type":"water","level":12,"hp":0}]}');
console.log(data.team.length);
console.log(data.team[0].name);
console.log(data.team[1].type);And because `data.team` is a real array, you can use array methods like `.map()` and `.filter()` directly on it to extract or filter the exact information your screen needs:
const data = JSON.parse('{"status":"ok","trainer":{"name":"Sam","badges":3},"team":[{"name":"Zap","type":"electric","level":4,"hp":45},{"name":"Aquachu","type":"water","level":12,"hp":0}]}');
const names = data.team.map((cdm) => cdm.name);
const ready = data.team.filter((cdm) => cdm.hp > 0);
console.log(names.join(", "));
console.log("Ready to fight: " + ready.length);Exercise 3 — Never Trust the Shape
Even when a server sends valid JSON, you cannot assume every property will always be there. If the server is busy or returns an error response, fields like `team` or `trainer` might be completely missing. Trying to read `data.team.length` when `data.team` is `undefined` immediately crashes with a `TypeError`:
const errorResponse = '{"status":"error","message":"Server busy"}';
const data = JSON.parse(errorResponse);
console.log(data.status);
console.log(data.team.length); // error!Two defensive habits keep your code safe: 1. Check the status first (`if (data.status === "ok")`) before accessing the main data. 2. Use optional chaining and nullish coalescing (`?.` and `??`) on optional fields so a missing property gently falls back to a default value instead of crashing:
const errorResponse = '{"status":"error","message":"Server busy"}';
const data = JSON.parse(errorResponse);
if (data.status === "ok") {
console.log("Team size: " + data.team.length);
} else {
console.log("Request failed: " + (data.message ?? "no details"));
}
console.log("Badges: " + (data.trainer?.badges ?? 0));Exercise 4 — Quiz: First Step
A server answer arrives in `response` as text. What must happen before you can read `response.team`?
Hint : Text has no keys until it is rebuilt into an object.
Exercise 5 — Quiz: Reach the Level
What does this code print?
const data = JSON.parse('{"team":[{"name":"Zap","level":4}]}');
console.log(data.team[0].level);4"Zap"undefinedHint : Follow the path: the array, its first object, then the property.
Exercise 6 — Parse and Navigate
Rebuild the response and print the trainer's name.
Hint : First turn the text into an object, then follow the path to the nested object.
Exercise 7 — The Safe Loading Pattern
When you combine all three defensive habits into a single function, you get the safe loading pattern used in real applications: 1. Layer 1 (`try...catch`): safely parses the text with `JSON.parse()` and stops if the JSON is broken. 2. Layer 2 (status check): checks `data.status !== "ok"` to handle server error messages cleanly. 3. Layer 3 (`?.` and `??`): reads nested fields with safe fallbacks in case optional properties are missing.
function loadTeam(response) {
let data;
try {
data = JSON.parse(response);
} catch (error) {
return "Invalid response";
}
if (data.status !== "ok") {
return "Server error: " + (data.message ?? "unknown");
}
return (data.team?.length ?? 0) + " Codémon loaded";
}
console.log(loadTeam('{"status":"ok","trainer":{"name":"Sam","badges":3},"team":[{"name":"Zap","type":"electric","level":4,"hp":45},{"name":"Aquachu","type":"water","level":12,"hp":0}]}'));
console.log(loadTeam('{"status":"error","message":"Server busy"}'));
console.log(loadTeam('{broken'));Whether the server sends a valid profile, an error message, or corrupted text, `loadTeam()` returns a clean, predictable result without ever crashing.
Exercise 8 — Quiz: Which Layer?
The server answered with valid JSON, but `status` is `"error"`. Which part of the safe pattern handles it?
Hint : Parsing worked fine here; the problem is what the answer says.
Exercise 9 — Fallback for a Missing Field
Print the badge count, or 0 when the trainer field is missing.
Hint : One symbol survives a missing link, the other replaces an empty answer.
Exercise 10 — Safe Loading Cheat Sheet
Match each problem with the tool that handles it.
?. and ??Exercise 11 — Profile Screen
Build the profile screen from a raw server response, handling every way it can go wrong.
Step 1: `showProfile(response)` parses the text inside a `try`. On failure it prints `"Corrupted response"` and stops. Step 2: if `status` isn't `"ok"`, it prints `"Error: message"` using the message, or `"unknown"` if there is none, and stops. Step 3: otherwise it prints `"Trainer: name (N badges)"`, then one line per team member as `"- name (type) Lv.X"`, then `"Fainted: N"` with the number of members at 0 HP. Step 4: call it on the three responses in `responses`.
Expected output:
Trainer: Sam (3 badges)
- Zap (electric) Lv.4
- Aquachu (water) Lv.12
Fainted: 1
Error: Server busy
Corrupted responseconst responses = [
'{"status":"ok","trainer":{"name":"Sam","badges":3},"team":[{"name":"Zap","type":"electric","level":4,"hp":45},{"name":"Aquachu","type":"water","level":12,"hp":0}]}',
'{"status":"error","message":"Server busy"}',
'{broken json'
];
// Write your function here
// Show the three profiles here