JSON.stringify() in JavaScript

Aug 16, 2019

The JSON.stringify() function is how you convert a JavaScript object to a JSON string. Just about every npm module that handles HTTP requests or responses, like Axios or Express, uses JSON.stringify() under the hood.

Converting Values to JSON

The first parameter to JSON.stringify() is the value to convert to JSON.

const obj = { answer: 42 };
const arr = ['hello', 'world'];

typeof JSON.stringify(obj); // 'string'

JSON.stringify(obj); // '{"answer":42}'
JSON.stringify(arr); // '["hello","world"]'

JSON can only represent values with the following types:

You may notice that this list excludes a few of JavaScript's built-in types. Specifically, JSON cannot represent JavaScript undefined, symbols, or BigInts. JSON.stringify() silently ignores undefined values and symbol values.

let obj = { undef: undefined, symbol: Symbol('foo') };

// JSON.stringify() ignores `undefined` and symbols
JSON.stringify(obj); // '{}'

JSON.stringify() throws an error if it finds a BigInt value.

// TypeError: Do not know how to serialize a BigInt
JSON.stringify({ val: 42n });

This list also excludes JavaScript objects, like JavaScript dates. The JSON.stringify() function converts JavaScript dates to strings.

// '{"date":"2019-06-01T00:00:00.000Z"}'
JSON.stringify({ date: new Date('2019-06-01') });

Replacer Function

The 2nd argument to JSON.stringify() is a replacer function. JavaScript calls this function for every key/value pair in the object, and uses the return value. If the replacer function returns undefined, that key is omitted from the JSON output.

For example, suppose you wanted to strip out null values using a replacer function:

const obj = { answer: 42, test: null };
// '{"answer":42}'
JSON.stringify(obj, function replacer(key, value) {
  if (value === null) {
    return undefined;
  }
  return value;
});

Pretty Printing

The 3rd argument to JSON.stringify() is called space. This parameter should be either a string or a number, and it tells JavaScript to format the JSON in a human readable way. If you specify a space parameter, JavaScript will put each key/value pair on its own line, and prefix each line with space.

const obj = { firstName: 'Jean-Luc', lastName: 'Picard' };
// {
//   "firstName": "Jean-Luc",
//   "lastName": "Picard"
// }
JSON.stringify(obj, null, '  ');
// Equivalent, JavaScript treats `space=2` as equivalent to 2 spaces.
JSON.stringify(obj, null, 2);

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials