What is JSON?

JSON (JavaScript Object Notation) is a text format for structured data, based on JavaScript object and array syntax, that has become the standard way to exchange data between servers, browsers, APIs and config files.

What JSON allows

  • Objects with double-quoted string keys: {"name": "Ada"}.
  • Arrays, strings (double quotes only), numbers, true, false and null.

What JSON does not allow

  • Single quotes, trailing commas, comments, or unquoted keys.
  • undefined, functions, Symbol, NaN, Infinity.
  • Date, Map, Set, BigInt or class instances as such. They must be converted to supported types first (e.g. a Date becomes an ISO string).

JSON vs JavaScript objects

A JavaScript object is a live value in memory; JSON is just text. You convert between them with JSON.stringify (value → text) and JSON.parse (text → value). fetch responses offer response.json(), which parses the body for you.

Where you see it

  • REST and many other web APIs.
  • package.json, tsconfig.json and other config files (some tools accept JSONC, which allows comments).
  • localStorage, which stores only strings, so objects are saved as JSON.

Safety

JSON.parse only builds data, it never runs code, so it is safe to use on untrusted input (unlike the old practice of eval). Still validate the shape of the data before trusting it, for example with a schema library like Zod.

Code example

js
1const user = {
2 name: "Ada",
3 joined: new Date("2024-01-15T00:00:00Z"),
4 tags: new Set(["admin"]),
5 score: NaN,
6 greet() {},
7 nickname: undefined,
8};
9
10const text = JSON.stringify(user);
11console.log(text);
12// {"name":"Ada","joined":"2024-01-15T00:00:00.000Z","tags":{},"score":null}
13// date -> string, Set -> {}, NaN -> null, functions and undefined dropped
14
15const back = JSON.parse(text);
16console.log(typeof back.joined); // "string" - not a Date any more
17
18// Valid vs invalid JSON
19for (const sample of ['{"ok":true}', "{'ok':true}", '{"a":1,}']) {
20 try {
21 JSON.parse(sample);
22 console.log("valid ", sample);
23 } catch {
24 console.log("invalid", sample);
25 }
26}
27
28// Convert unsupported types yourself
29const safe = { ...user, tags: [...user.tags] };
30console.log(JSON.stringify(safe.tags)); // ["admin"]

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app