JSON in JavaScript: turning data into text and back

JSON is the data exchange format of the web. JavaScript handles it with just two methods: stringify to write, parse to read.
3 min read
Believemy logo

As soon as data leaves a program, it has to become text. A network request, a configuration file, a value stored in the browser: all these channels carry characters, not objects.

JSON is the format that won that place. Its syntax comes from JavaScript, a human can read it, and its entire usage fits into two methods.


Definition

JSON, short for JavaScript Object Notation, is a text format for representing structured data. In JavaScript, the built-in JSON object exposes two methods: stringify, which turns a value into text, and parse, which makes the return trip.

JAVASCRIPT
const cart = { items: 2, total: 98, paid: false };

const text = JSON.stringify(cart);
console.log(text);
// '{"items":2,"total":98,"paid":false}'

const back = JSON.parse(text);
console.log(back.total + 1);  // 99

A third argument indents the output, which makes a file readable: JSON.stringify(cart, null, 2). The second argument, used far less often, filters which keys to keep.


What JSON cannot carry

The format knows only six kinds of value: string, number, boolean, array, object and null. Everything else disappears or silently changes nature.

Original valueAfter a round trip
undefinedThe key disappears
A functionThe key disappears
NaN, Infinitynull
A Date objectA string in ISO format
A Map, a SetAn empty object

The date case is the most common and the quietest: after parse, the value is a String, no longer an object. It has to be rebuilt with new to get its methods back.

Good to know

Key names must sit in double quotes inside a JSON file, and a trailing comma is forbidden. That is the most frequent syntax difference with an Object written in JavaScript.


Reading text received from outside

JSON.parse throws as soon as the text is malformed, and an interrupted network response is enough to produce that case. The call therefore has to be guarded.

JAVASCRIPT
function read(text) {
  try {
    return JSON.parse(text);
  } catch (error) {
    console.log("invalid JSON:", error.message);
    return null;
  }
}

console.log(read('{"ok":true}'));  // { ok: true }
console.log(read("{oops}"));       // null

The try and catch pair is mandatory here, not decorative: without it the error bubbles up and interrupts the rest of the processing.


Frequently asked questions

Question

Can I copy an object with JSON?

The JSON.parse(JSON.stringify(object)) trick works and produces a deep copy, but it loses everything the format cannot carry: dates, functions, undefined values. The structuredClone() function, available in modern browsers and in Node, does the same job without those losses.


Question

Why do my accented characters come out garbled?

It is almost never JSON, which works in UTF-8, but the header sent with the response or the encoding of the file itself. Check that the server announces application/json; charset=utf-8 before looking any further, and that the file is saved as UTF-8.


Question

Does JSON allow comments?

No, and that is deliberate: the format was designed for data exchange, not for readable configuration. This is what led some tools to accept tolerant variants such as JSONC. In a standard configuration file, a comment makes JSON.parse fail with a syntax Error.

Related terms

Discover our javaScript glossary

Every word of JavaScript explained simply: keywords, built-in objects, methods, errors and concepts. Clear definitions and examples that actually run, to learn and to troubleshoot.

Share this article

Want to help us? Share this article on your networks or even better: on your site, in an article or in your newsletter.