Convert Object or Value to JSON String
2 min read

Convert Object or Value to JSON String

The JSON.stringify() is used to convert a JavaScript object or a value to JSON serialized string.

JSON

The JSON is an inbuilt object provided by javascript. This contains methods for parsing a JSON string into an object or converting it to JSON serialized string.

JSON.stringify()

This stringify method is used to create a serialized string.

Syntax

JSON.stringify(value, replacer, space)

Parameters

value

The value can be an object, an array, a number, a string, a boolean, or null. The input value gets converted into a serialized string.

Here are some examples using JSON.stringify:

JSON.stringify({});                    
// Output => '{}'

JSON.stringify(true);
// Output => 'true'

JSON.stringify('foo'); 
// Output => '"foo"'

JSON.stringify([1, 'false', false]);
// Output => '[1,"false",false]'

JSON.stringify([NaN, null, Infinity]);
// Output => '[null,null,null]'

JSON.stringify({ x: 5 });
// Output => '{"x":5}'

If a JavaScript object has a toJSON() method, then that method is responsible for serialized data conversion.

const person = {
    name: 'John',
    age: 20,
    gender: 'male',
    toJSON: function() {
        return {
            name: this.name,
            age: this.age,
        };
    }
};

JSON.stringify(person);
// Output => '{"name":"John","age":20}'

The undefined, function and symbol are not valid JSON values. Such values are omitted when found in an object or converted to null when found in an array.

const person = {
    first_name: 'John',
    last_name: 'Doe',
    age: undefined,
    getFullName: function() {
        return `${this.first_name} ${this.last_name}`;
    },
    id: Symbol(),
};

JSON.stringify(person);
// Output => '{"first_name":"John","last_name":"Doe"}'

JSON.stringify([undefined, function getFullName() {}, Symbol()]);
// Output => '[null,null,null]'

The JSON.stringify method returns undefined if a pure non-valid JSON value is passed.

JSON.stringify(undefined);
// Output => undefined

JSON.stringify(function getFullName() {});
// Output => undefined

JSON.stringify(Symbol());
// Output => undefined

The numbers Infinity and NaN, as well as the value null, are all converted null.

JSON.stringify(Infinity);
// Output => 'null'

JSON.stringify(NaN);
// Output => 'null'

JSON.stringify(null);
// Output => 'null'

The non-enumerable properties of an object will not be serialized.

const abObject = { 
    a: { 
        value: '1', 
        enumerable: false
    }, 
    b: { 
        value: '2', 
        enumerable: true
    } 
};

JSON.stringify(Object.create(null, abObject));
// Output => '{"b":"2"}'

replacer - Optional

The replacer can be a function or an array of strings and numbers to allow properties of an object.

Here is an example of a function as a replacer:

function replacer(key, value) {
  if (typeof value === 'string') {
    return undefined;
  }
  return value;
}

const obj = {
    name: 'John',
    age: 21,
};

JSON.stringify(obj, replacer);
// Output => '{"age":21}'

Here is an example of properties allow list as a replacer:

const obj = {
    name: 'John',
    age: 21,
};

JSON.stringify(obj, ['age']);
// Output => '{"age":21}'

space - Optional

The space argument is used to control spacing in the final serialized string.

const obj = {
    name: 'John',
    age: 21,
};

JSON.stringify(obj, ['age'], ' ');
// Output => '{ "age":21}'

Errors Conditions

  1. The JSON.stringify() throws an error if the length of the serialized string is more than the max string length supported by the JavaScript engine.
  2. The JSON.stringify() throws TypeError when serialising circular references.