JSON Parsing

What is JSON parsing?

JSON parsing converts text (JSON format) into JavaScript objects. This lets you work with data received from servers, files, or APIs.

Benefits of JSON parsing?

  • Convert text to usable objects
  • Receive data from web servers
  • Store and load game data
  • Work with APIs
  • Share data between programs
// JSON to object
const jsonString = '{"name": "Guard", "health": 100, "level": 5}';
const gameData = JSON.parse(jsonString);

console.log(gameData.name); // Guard
console.log(gameData.health); // 100

// Object to JSON
const player = {
    name: "Astro",
    health: 100,
    level: 10
};

const jsonData = JSON.stringify(player);
console.log(jsonData); // {"name":"Astro","health":100,"level":10}

What does this code do?

  • JSON.parse() converts text to JavaScript object
  • Can now access properties like regular objects
  • JSON.stringify() converts object back to text
  • Useful for storing and sending data
  • Both are essential for working with APIs and files
// Parsing array of game objects
const gameDataJson = '[{"type":"guard","x":200,"y":100},{"type":"npc","x":300,"y":150}]';
const gameObjects = JSON.parse(gameDataJson);

gameObjects.forEach(obj => {
    console.log(obj.type + " at (" + obj.x + ", " + obj.y + ")");
});

What does this code do?

  • Parses JSON array containing game objects
  • Converts text into usable JavaScript array
  • Loops through parsed objects
  • Shows how to work with data from servers
  • Demonstrates JSON parsing with complex data structures

Try It Yourself

%%js // CODE_RUNNER: json-parsing const jsonString = ‘{“name”:”Player”,”level”:5,”items”:[“sword”,”shield”]}’; const player = JSON.parse(jsonString); console.log(player.name); console.log(player.items[0]); const jsonOut = JSON.stringify(player); console.log(jsonOut);