JSON
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.
{ "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.
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
const course = { title: 'SQL', chapters: 5 };
JSON.stringify(course); // '{"title":"SQL","chapters":5}'
JSON.stringify(course, null, 2); // pretty-printed with 2-space indentsThe pretty-printed version looks like this — useful for files and debugging:
{
"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:
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 propertyObjects can also control their own JSON by having a toJSON() method. Dates have one, which is why they become ISO strings.
Text → object
const text = '{"title":"SQL","chapters":5}';
const data = JSON.parse(text);
data.chapters; // 5JSON.parse throws a SyntaxError on invalid text, so wrap it in try/catch when the text comes from outside your code:
JSON.parse("{'title': 'SQL'}"); // SyntaxError — single quotes aren't JSON
JSON.parse(''); // SyntaxError — empty string isn't JSONReviving 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:
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(); // 2026What gets lost
JSON.stringify({ when: new Date(2026, 0, 1), fn() {}, missing: undefined });
// '{"when":"2026-01-01T…Z"}' — the date becomes a string; fn and missing disappearDates come back as strings. After parsing, turn them back with
new Date(data.when).
Other conversions to watch for:
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 supportedObjects 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:
const response = await fetch('/api/courses');
const courses = await response.json();And to send data, you stringify it:
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:
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.
Safe parse
Write safeParse(text, fallback) that returns the parsed value, or fallback (default null) if the text isn’t valid JSON.
function safeParse(text, fallback) {
// your code here
}
safeParse('{"a":1}'); // { a: 1 }
safeParse('oops'); // null
safeParse('oops', []); // []function safeParse(text, fallback = null) {
try {
return JSON.parse(text);
} catch {
return fallback;
}
}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.stringifyturns a value into text;JSON.parseturns text back into a value.JSON.parsethrows on invalid text — wrap it intry…catchfor outside data.- Dates come back as strings; functions,
undefined, Maps and Sets don’t survive.