How to work with JSON

Understand JSON

JSON is a text data format, not a JavaScript object. It supports objects, arrays, strings, numbers, booleans, and null; property names and strings use double quotes.

{
  "name": "Amina",
  "completed": 8,
  "topics": ["arrays", "objects"],
  "active": true
}

Convert data to JSON

JSON.stringify serializes supported JavaScript data. Functions and undefined object properties are omitted.

const learner = { name: "Amina", completed: 8 };
const compact = JSON.stringify(learner);
const readable = JSON.stringify(learner, null, 2);
console.log(compact);
console.log(readable);

Parse JSON text

JSON.parse returns the represented JavaScript value and throws SyntaxError for malformed input.

const text = '{"name":"Amina","completed":8}';
const learner = JSON.parse(text);
console.log(learner.name);
console.log(learner.completed + 1);

Handle and validate external JSON

Parsing proves only that syntax is valid. Check the resulting shape and types before the rest of the program depends on them.

function parseLearner(text) {
  const value = JSON.parse(text);
  if (!value || typeof value.name !== "string") {
    throw new TypeError("Invalid learner data");
  }
  return value;
}

try {
  console.log(parseLearner('{"name":"Kai"}'));
} catch (error) {
  console.error(error.message);
}