Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 156 ยท Objects

JSON

Convert JavaScript values to JSON text and back with JSON.stringify and JSON.parse. Learn formatting, replacers, revivers, dates, undefined and other pitfalls.

JSON (JavaScript Object Notation) is a text format for structured data. It looks almost exactly like JavaScript object and array literals, which is no accident: it was derived from them. Today it is the common language of the web. APIs send JSON, configuration files are written in it, and browsers store it in localStorage.

Because JSON is just text, you need to convert between it and real JavaScript values. JSON.stringify() turns a value into a JSON string (serializing), and JSON.parse() turns a JSON string back into a value (parsing). Both are built into every JavaScript environment. This lesson covers the rules of the format, both functions and their optional extras, and the pitfalls that catch almost everyone at least once.

What JSON looks like

JSON supports exactly six kinds of values:

JSON type Example
Object {"name": "Ana", "age": 31}
Array [1, 2, 3]
String "hello"
Number 42, -3.5, 1e6
Boolean true, false
Null null

It is stricter than JavaScript in several ways:

  • Property names must be in double quotes: {"id": 1}, never {id: 1}.
  • Strings use double quotes only. Single quotes and backticks are not allowed.
  • No trailing commas, no comments, no undefined, no functions.
  • Numbers can't be NaN, Infinity, hex (0xFF) or have a leading + or leading zeros.

A typical JSON document looks like this:

JSON
{
  "id": 1042,
  "title": "Learn JSON",
  "done": false,
  "tags": ["javascript", "data"],
  "assignee": null
}

JSON.stringify(): values to text

Pass any value to JSON.stringify() and you get a string back:

JS Serializing values

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The output is compact, with no spaces, which is ideal for sending over a network. Notice that stringifying a string adds quotes: the result is the JSON text "hi", quotes and all.

Pretty printing

The third argument adds indentation, which makes JSON readable for humans, in log files or a config you will save to disk. Pass a number of spaces (up to 10) or a string such as "\t":

JavaScript
console.log(JSON.stringify(task, null, 2));
// {
//   "id": 1042,
//   "title": "Learn JSON",
//   ...
// }

The second argument (here null) is the replacer, covered below.

What can't be serialized

JSON has fewer types than JavaScript, so JSON.stringify() has to decide what to do with the rest. Its choices are worth memorizing, because they fail silently:

JS Values JSON can't represent

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Here is what happened:

  • In objects, properties whose value is undefined, a function or a symbol are dropped.
  • In arrays, those same values become null, so positions don't shift.
  • NaN and Infinity become null.
  • A Date becomes an ISO 8601 string, because dates have a toJSON() method.
  • Set and Map become {}, since they have no own enumerable properties. Convert them first, for example with [...set] or Object.fromEntries(map).
  • A BigInt throws a TypeError.
  • An object that contains itself (a circular reference) also throws.

toJSON()

If an object has a toJSON() method, JSON.stringify() calls it and serializes whatever it returns instead. That's how Date turns itself into a string, and you can use it in your own classes:

JavaScript
class Money {
  constructor(cents, currency) {
    this.cents = cents;
    this.currency = currency;
  }
  toJSON() {
    return `${(this.cents / 100).toFixed(2)} ${this.currency}`;
  }
}

console.log(JSON.stringify({ total: new Money(1999, "EUR") }));
// {"total":"19.99 EUR"}

JSON.parse(): text to values

JSON.parse() reads a JSON string and builds fresh JavaScript values from it:

JS Parsing JSON

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Malformed input throws a SyntaxError, so any JSON that comes from outside your program (a user, a file, a server, storage) should be parsed inside try...catch. You'll learn more about that in Errors and try...catch. A small helper keeps it tidy:

JavaScript
function safeParse(text, fallback = null) {
  try {
    return JSON.parse(text);
  } catch {
    return fallback;
  }
}

safeParse('{"ok":true}'); // { ok: true }
safeParse("oops", {});    // {}

Replacers: controlling the output

The second argument of JSON.stringify() is a replacer. It comes in two forms.

An array of keys acts as an allow-list. Only those property names are included, at every level:

JavaScript
const user = { id: 9, name: "Rosa", email: "[email protected]", passwordHash: "x9f..." };
console.log(JSON.stringify(user, ["id", "name"]));
// {"id":9,"name":"Rosa"}

A function is called for every key and value. Whatever it returns is used instead; returning undefined removes the property:

JS A replacer function

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The function is first called with an empty key "" and the whole value, then for each property as it walks down the tree. Always return value for anything you don't want to change, or you'll accidentally drop it.

Revivers: rebuilding special values

On the way back, a JSON string can't tell you that "2026-03-14T09:30:00.000Z" used to be a Date. It just comes back as a string. The second argument of JSON.parse() is a reviver function that lets you fix values as they are parsed:

JS Reviving dates

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Like a replacer, a reviver sees every key and value, and must return value for everything it leaves alone. Matching by key name is the safest strategy. Guessing from the shape of a string (anything that looks like a date) can turn ordinary text into dates by mistake.

Common uses and pitfalls

You'll use these two functions all the time:

  • Talking to servers. fetch() responses have a .json() method that parses for you, and you send data with body: JSON.stringify(data). See Fetching Data with fetch().
  • Saving to storage. localStorage only stores strings, so you stringify on the way in and parse on the way out.
  • Debugging. JSON.stringify(obj, null, 2) gives a quick, readable snapshot of plain data.
  • Deep copying. JSON.parse(JSON.stringify(obj)) was the classic trick, but it loses dates, undefined, Maps and more. Modern code uses structuredClone() instead, as you'll see in the next lesson.

Never use eval() to read JSON. Old tutorials sometimes did. eval() runs any code inside the string, so data from an attacker becomes code. JSON.parse() only ever builds data.

Keep in mind that JSON is a data format. It can't store functions, class instances, prototypes or references between objects. When you parse JSON, you always get plain objects and arrays back, even if you stringified a Money or a Temperature.

JSON in the wider world

JSON versus a JavaScript object

They look alike because JSON was borrowed from JavaScript's object literal syntax, but they are different things: JSON is text, a JavaScript object is a live value in memory.

JSON text JavaScript object literal
Keys always double-quoted strings identifiers, strings, numbers or computed keys
Strings double quotes only single, double or backtick quotes
Values string, number, true, false, null, array, object anything, including undefined, functions, dates, Maps, class instances
Comments and trailing commas not allowed allowed
Lives in a file, a network message, a database column in memory, inside a running program

Converting between them has two names. Serialization (JavaScript value to text) is JSON.stringify(). Deserialization (text to JavaScript value) is JSON.parse(). Every language has its own pair, which is why JSON works as a common language between a Laravel backend, a Go service and a browser.

Comments in JSON

Standard JSON has no comments, and a parser rejects them. If a config file needs notes, you have these options:

  • Add a normal field that carries the note, such as "_comment": "timeout is in milliseconds". The data stays valid; your code simply ignores the key.
  • Use a superset format made for humans, such as JSON5 or JSONC (the format VS Code's settings use), and strip the comments with a tool before calling JSON.parse().
  • Keep the explanation next to the file, in documentation or in a schema.
JS Why comments fail, and the _comment workaround

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Maps and Sets are not JSON

JSON.stringify() turns a Map or a Set into {}, because they keep their data in internal slots, not in properties. Convert them to arrays first. The Map's entries array is a natural fit because it preserves every key, even keys that are not strings. When you read the text back, rebuild the collection with the constructor.

JS Map and Set to JSON and back

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The trade-off: Object.fromEntries() gives friendlier JSON but turns numeric keys into strings and merges keys that print the same; the entries array keeps them apart.

Blob data to JSON

A Blob (a file the user picked, or a response body you fetched) holds raw bytes. To get an object out of it, read it as text and parse that. blob.text() returns a promise, so use await.

JS From Blob to JSON

Press Run (or Ctrl + Enter) to see the console output here.

No output.

For a file input, call file.text() the same way. More on files in Files and Blobs.

JSON compared with XML and binary formats

JSON and XML are both text formats that are human readable, self-describing, hierarchical, language independent and parsed by libraries in every language. JSON wins on size and simplicity: no closing tags, native numbers, booleans and arrays, and one call to parse it in JavaScript. XML wins where you need attributes, namespaces, mixed content (text with markup inside), comments and mature schema and transformation tools.

JSON's disadvantages: no comments, no date type (dates become strings), no distinction between integers and floats (every number is read as a JavaScript double, so very large integers lose precision), no way to hold binary data except by encoding it as text such as Base64, and no built-in schema.

Binary relatives keep the JSON data model but store it more compactly:

  • BSON ("binary JSON") is the storage format of MongoDB. It adds types JSON lacks (dates, 64-bit integers, binary data) and length prefixes so the database can skip over fields quickly. It is not meant for people to read or for browsers to parse.
  • MessagePack and CBOR are general-purpose compact formats for messages; CBOR is the one standardized for small devices and signing.

For public web APIs, plain JSON remains the default; reach for a binary format when message size or parse speed has been measured as a real problem.

JSON Schema

JSON has no built-in way to say "this must be a number between 1 and 5". JSON Schema is a separate standard that describes the allowed shape of a JSON document, as JSON itself. Tools validate documents against it on the server, in editors and in API gateways.

JSON
{
  "type": "object",
  "properties": {
    "name": { "type": "string", "minLength": 1 },
    "rating": { "type": "integer", "minimum": 1, "maximum": 5 }
  },
  "required": ["name"],
  "additionalProperties": false
}

Here required lists mandatory keys, minimum and maximum bound a number, and "additionalProperties": false rejects any key the schema does not mention, which catches typos. JavaScript has no validator built in; libraries such as Ajv implement the standard. To see the idea, here is a small hand-made checker for just these rules:

JS A tiny schema validator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Sending JSON safely

  • Use HTTPS so the text is encrypted in transit; JSON itself has no encryption or signing.
  • Never put secrets in the body of a public response, and validate incoming JSON on the server every time, because anyone can send anything.
  • Parse with JSON.parse(), never eval().
  • Set Content-Type: application/json and parse inside try...catch.

When you debug, a JSON formatter pretty-prints text and a JSON validator points at the exact line and character that breaks the syntax; browser DevTools, editors and JSON.stringify(value, null, 2) all do the first job, and a failed JSON.parse() gives you the second.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does JSON.stringify({ a: undefined, b: 1 }) return?

    Object properties holding undefined (or functions or symbols) are dropped. In arrays they would become null instead.
  2. 2. Which string is valid JSON?

    JSON requires double-quoted keys and strings and forbids trailing commas.
  3. 3. You stringify { when: new Date() } and parse it again. What is when now?

    Dates serialize through toJSON() to ISO strings, and JSON.parse() has no way to know it was a date. Use a reviver to turn it back.
  4. 4. What happens when JSON.parse() receives malformed text?

    Invalid JSON throws, so wrap parsing of outside data in try...catch.
  5. 5. In a replacer function, what does returning undefined for a property do?

    Returning undefined for an object property leaves it out. Return value for anything you don't want to change.

Summary

  • JSON is a strict text format: double-quoted keys and strings, no comments, no trailing commas, six value types.
  • JSON.stringify(value, replacer, indent) turns values into text; use null, 2 for readable output.
  • undefined, functions and symbols are dropped from objects (and become null in arrays); NaN and Infinity become null; BigInt and circular references throw.
  • Dates become ISO strings via toJSON(), and you can add toJSON() to your own classes.
  • JSON.parse(text, reviver) rebuilds plain values and throws a SyntaxError on bad input, so guard it with try...catch.
  • A reviver can restore dates and other special values by key.

Next: Copying Objects: Shallow and Deep โ€” references, shallow copies and structuredClone().