JSON: stringify, parse and what it cannot hold

JSON is the text format that carries data between programs, and it has two functions in the language: JSON.stringify writes a value as text and JSON.parse reads the text back. The format holds objects, arrays, strings, numbers, booleans and null, and it holds nothing else, so a value outside that list is converted, dropped or refused.

The conversion is the part that costs programs their data: a date becomes a string, an undefined property disappears and a bigint stops the whole call. This lesson writes and reads a record, uses the two optional arguments that shape the text, and then prints what each kind of value becomes. A program that stores its own state as JSON needs every line of that section.

stringify

JSON.stringify returns a string with no spaces, and the keys keep the order in which the object holds them. A string, a number and a boolean are written as themselves, an array keeps its order and an object becomes a pair of braces with quoted names. The result is a single line, which is what a file or a socket wants.

const user = { id: 7, name: 'Ada', tags: ['math', 'code'], address: { city: 'London' }, }; console.log(JSON.stringify(user)); console.log('typeof:', typeof JSON.stringify(user)); console.log(JSON.stringify([1, 'two', true, null])); console.log(JSON.stringify('text')); console.log(JSON.stringify(42));

node stringify.js

{"id":7,"name":"Ada","tags":["math","code"],"address":{"city":"London"}}
typeof: string
[1,"two",true,null]
"text"
42

The record came out with quoted names in the order it was written, and the nested array and object kept their shape. The three scalar lines are the reminder that the function accepts any value: a string becomes a quoted string, a number becomes its digits and an array of mixed values stays an array. The result of the first line is what a reader of the file sees, so a program that logs a request body logs exactly this text.

Indentation and a replacer

The third argument is the indentation: a number is that many spaces and a string is the text to indent with. The second argument decides which properties are written, either as a list of names or as a function that returns the value to write and undefined to leave the property out. That function is how a program removes a password before it writes a record.

const user = { id: 7, name: 'Ada', password: 'secret', admin: true }; console.log(JSON.stringify(user, null, 2)); console.log('only two keys:', JSON.stringify(user, ['id', 'name'])); console.log( 'without the password:', JSON.stringify(user, (key, value) => (key === 'password' ? undefined : value)) );

node indent.js

{
"id": 7,
"name": "Ada",
"password": "secret",
"admin": true
}
only two keys: {"id":7,"name":"Ada"}
without the password: {"id":7,"name":"Ada","admin":true}

The indented form is for a person and the one-line form is for a program, and both parse to the same value. The array of names kept two properties and dropped the other two without a warning, which is useful for a summary and dangerous for a backup. The function form left the password out and kept everything else, and for the whole object it receives the empty string as the key, which is worth knowing in a filter that tests the key.

parse and a reviver

JSON.parse reads text and returns the value it describes, and it throws a SyntaxError for anything the format does not allow: a name without quotes, a trailing comma, a comment. The second argument is a reviver, a function that sees every key and value and returns what should stand in its place, which is where a date string becomes a Date again.

const text = '{"id":7,"born":"1815-12-10T00:00:00.000Z"}'; const plain = JSON.parse(text); console.log('id:', plain.id); console.log('born type:', typeof plain.born); const revived = JSON.parse(text, (key, value) => key === 'born' ? new Date(value) : value ); console.log('revived type:', revived.born instanceof Date); console.log('year:', revived.born.getUTCFullYear()); try { JSON.parse('{name: "Ada"}'); } catch (error) { console.log(error.name + ': ' + error.message); }

node parse.js

id: 7
born type: string
revived type: true
year: 1815
SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)

The first read gave a string where the program wrote a date, and the reviver turned it back into one before the value reached the rest of the code. A reviver runs on every property from the inside out, so it has to test the key rather than assume the shape. The caught error names what the reader expected and the position of the character that broke the format, so a log line points at the bad byte.

What JSON cannot hold

The format has six kinds of value, and everything else is treated as follows: a property whose value is undefined or a function is left out of an object, the same values become null inside an array, NaN and Infinity become null, and a date becomes a string through its toJSON method. A bigint and a value that contains itself stop the call with an error.

console.log('undefined in an object:', JSON.stringify({ a: undefined, b: 1 })); console.log('undefined in an array:', JSON.stringify([undefined])); console.log('a function:', JSON.stringify({ run: () => 1 })); console.log('NaN and Infinity:', JSON.stringify([NaN, Infinity])); console.log('a date:', JSON.stringify({ at: new Date('2024-05-17T00:00:00Z') })); const loop = {}; loop.self = loop; try { JSON.stringify(loop); } catch (error) { console.log(error.name + ': ' + error.message); } try { JSON.stringify({ id: 1n }); } catch (error) { console.log(error.name + ': ' + error.message); }

node limits.js

undefined in an object: {"b":1}
undefined in an array: [null]
a function: {}
NaN and Infinity: [null,null]
a date: {"at":"2024-05-17T00:00:00.000Z"}
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Object'
--- property 'self' closes the circle
TypeError: Do not know how to serialize a BigInt

The property with undefined disappeared and the array element became null, which is the difference between a missing key and a key with no value. The date survived as text because the serialiser calls toJSON, and the reader has to call Date on it as the reviver did. The two errors are the good ones: the cycle names the property chain and the bigint is refused rather than rounded.

Exercises

  1. Add undefined to the array in stringify.js. Which value stands in its place in the text?
  2. Pass 4 as the third argument in indent.js and compare the output with the two-space form. Which lines change?
  3. Pass a replacer function to stringify that returns undefined for every key. What does the call return, and why?
  4. Parse 'null' and '42' in parse.js. Which values arrive, and what does typeof say about each?
  5. Put a Map in an object and stringify it. What does the text show, and where did the entries go?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does this program print? console.log(JSON.stringify({ a: 1 }));

    Answer

    {"a":1}

    The one-line form has quoted names and no spaces, and indentation is a separate argument.

  2. What does this program print? console.log(JSON.stringify({ a: undefined, b: 1 }));

    Answer

    {"b":1}

    A property whose value is undefined is left out of an object.

  3. What does this program print? console.log(JSON.stringify([undefined]));

    Answer

    [null]

    Inside an array the position has to stay, so the value becomes null.

  4. What does this program print? console.log(JSON.stringify([NaN, Infinity]));

    Answer

    [null,null]

    The format has no NaN and no Infinity, so both are written as null.

  5. What does JSON.stringify do with a Date?

    Answer

    It calls toJSON and writes the ISO string

    The date carries a toJSON method, and the serialiser uses its return value.

  6. What does JSON.stringify do with a bigint?

    Answer

    It throws a TypeError

    The format has no integer type beyond a float, so the serialiser refuses the value.

  7. What does JSON.stringify do with an object that contains itself?

    Answer

    It throws a TypeError about a circular structure

    The serialiser follows the graph and reports the cycle with the property chain.

  8. What does this program print? console.log(JSON.stringify({ id: 7 }, ['id', 'name']));

    Answer

    {"id":7}

    The array is a list of names to keep, and a name that the object does not have adds nothing.

  9. What does this program print? console.log(typeof JSON.parse('42'));

    Answer

    number

    The text 42 is a number in the format, and parse returns a number.

  10. What happens with JSON.parse('{name: "Ada"}')?

    Answer

    It throws a SyntaxError, because the name is not quoted

    The format requires quoted names, and the reader refuses the text instead of guessing.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev