JSON

Topic 5 of 5 in Objects6 min readBeginnerFree course

Overview

JSON (JavaScript Object Notation) is a text format for data. Web APIs send it, config files use it (package.json is one), and you’ll store it in the browser.

JSON
{ "title": "JavaScript Essentials", "chapters": 14, "tags": ["web", "beginner"] }

Why text? Data has to travel — across a network, into a file, into localStorage — and only text can make that journey. JSON is a simple, agreed way to write data as text that any language can read: Python, Java, PHP and Go all have JSON libraries.

A JavaScript object with title ‘SQL’ and chapters 5 is turned into JSON text by JSON.stringify, sent over the network or saved, then turned back into a new object by JSON.parse. Below, a table of what survives: strings, numbers, booleans, null, arrays and plain objects are kept; dates become strings; NaN and Infinity become null; undefined and functions are dropped; Maps and Sets become empty objects.

JSON syntax rules

It looks like a JavaScript object, but keys must be in double quotes, and only strings, numbers, booleans, null, arrays and objects are allowed. JSON is stricter than JavaScript:

Allowed in JavaScript objects In JSON?
{ title: 'SQL' } — unquoted key, single quotes ✗ must be { "title": "SQL" }
Trailing comma [1, 2,] ✗
Comments // … ✗
undefined, NaN, Infinity ✗
Functions, dates, Maps ✗
Nested objects and arrays ✓

A JSON document can be any JSON value at the top level — an object, an array, or even a lone string or number.

Object → text

JavaScript
const course = { title: 'SQL', chapters: 5 };
JSON.stringify(course);          // '{"title":"SQL","chapters":5}'
JSON.stringify(course, null, 2); // pretty-printed with 2-space indents

The pretty-printed version looks like this — useful for files and debugging:

JSON
{
  "title": "SQL",
  "chapters": 5
}

Choosing what to include

The second argument of stringify filters the output. Pass an array of keys to keep, or a function to transform values:

JavaScript
const user = { name: 'Asha', email: 'asha@example.com', password: 'secret' };

JSON.stringify(user, ['name', 'email']);
// '{"name":"Asha","email":"asha@example.com"}'

JSON.stringify(user, (key, value) => (key === 'password' ? undefined : value));
// same result — returning undefined drops a property

Objects can also control their own JSON by having a toJSON() method. Dates have one, which is why they become ISO strings.

Text → object

JavaScript
const text = '{"title":"SQL","chapters":5}';
const data = JSON.parse(text);
data.chapters; // 5

JSON.parse throws a SyntaxError on invalid text, so wrap it in try/catch when the text comes from outside your code:

JavaScript
JSON.parse("{'title': 'SQL'}"); // SyntaxError — single quotes aren't JSON
JSON.parse('');                  // SyntaxError — empty string isn't JSON

Reviving values

parse accepts a second argument too: a reviver function that can transform values as they’re read. It’s a tidy way to turn date strings back into Date objects:

JavaScript
const json = '{"title":"Launch","when":"2026-01-01T09:00:00.000Z"}';
const event = JSON.parse(json, (key, value) =>
  key === 'when' ? new Date(value) : value,
);
event.when.getFullYear(); // 2026

What gets lost

JavaScript
JSON.stringify({ when: new Date(2026, 0, 1), fn() {}, missing: undefined });
// '{"when":"2026-01-01T…Z"}' — the date becomes a string; fn and missing disappear

Dates come back as strings. After parsing, turn them back with new Date(data.when).

Other conversions to watch for:

JavaScript
JSON.stringify([undefined, () => {}]); // '[null,null]' — in arrays they become null
JSON.stringify({ n: NaN });            // '{"n":null}'
JSON.stringify(new Map([['a', 1]]));   // '{}' — convert first: Object.fromEntries(map)
JSON.stringify({ big: 10n });          // TypeError — BigInt isn't supported

Objects that refer to themselves (circular references) also throw: TypeError: Converting circular structure to JSON.

Where you’ll use JSON

Talking to APIs. fetch gives you a response whose .json() method parses the body for you:

JavaScript
const response = await fetch('/api/courses');
const courses = await response.json();

And to send data, you stringify it:

JavaScript
await fetch('/api/courses', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ title: 'SQL' }),
});

Saving in the browser. localStorage only stores strings, so objects go in as JSON:

JavaScript
localStorage.setItem('settings', JSON.stringify({ theme: 'dark' }));
const settings = JSON.parse(localStorage.getItem('settings') ?? '{}');

You’ll see both of these in detail in The Fetch API and Web storage.

Debugging. JSON.stringify(value, null, 2) gives a readable snapshot of an object at one moment — handy when the console’s live view of an object has changed by the time you look at it.

Exercise

Safe parse

Write safeParse(text, fallback) that returns the parsed value, or fallback (default null) if the text isn’t valid JSON.

JavaScript
function safeParse(text, fallback) {
  // your code here
}

safeParse('{"a":1}');      // { a: 1 }
safeParse('oops');          // null
safeParse('oops', []);      // []

Summary

  • JSON is a text format for data, used by APIs, config files and browser storage.
  • JSON keys and strings need double quotes; no comments, trailing commas, functions or undefined.
  • JSON.stringify turns a value into text; JSON.parse turns text back into a value.
  • JSON.parse throws on invalid text — wrap it in try…catch for outside data.
  • Dates come back as strings; functions, undefined, Maps and Sets don’t survive.