JSON Parsing
Input / Output · Parse API responses (leaderboard data, AI responses).
JSON Parsing
What it is
JSON (JavaScript Object Notation) is the standard text format for sending structured data over the network. JSON.parse(str) converts a JSON string into a JavaScript object; response.json() is the Promise-based version for Fetch responses. Destructuring (const { a, b } = obj) extracts named properties cleanly.
Why it matters
APIs communicate in JSON. Parsing is required to use the data. Destructuring makes the parsed-data access readable instead of writing data.scores[0].value every time.
How GateGame implements it
Leaderboard responses come back as JSON arrays like [{ user: 'aarav', score: 4200 }, ...]. await response.json() parses them into usable JS arrays. Destructuring extracts the top score cleanly: const { scores } = await response.json(). The NPC AI response is similarly parsed and destructured for message and emotion fields.
Code Example
// Parse a fetch response
const res = await fetch('/api/leaderboard');
const data = await res.json(); // parse JSON → JS object
const topScore = data.scores[0].value;
// Destructure for cleaner access
const { scores } = await res.json();
const [first, second, third] = scores;
Key Takeaway
response.json()does the parsing for you. Destructure into clean local variables instead of dot-chaining everywhere.