What's the difference in using toString() compared to JSON.stringify()?

Unless you have a custom object with custom .toString method returning JSON.stringify of that object, there is no obj that would give obj.toString() == JSON.stringify(obj).

When obj is an array like [1,2,3] then .toString() gives:

"1,2,3"

And JSON.stringify:

"[1,2,3]"

These are close but not quite the same, the JSON serialized one has no ambiguity with commas and directly runs as Javascript or can be parsed as JSON.

See:

["1,",2,3].toString();
//"1,,2,3" ... so you can't just split by comma and get original array
//it is in fact impossible to restore the original array from this result

JSON.stringify(["1,",2,3])
//'["1,",2,3]'
//original array can be restored exactly

for an object say

obj = { a: 'a', '1': 1 }

obj.toString() gives

"[object Object]"

JSON.stringify(obj) gives

"{"1":1,"a":"a"}"

For .toString(), a default value is returned when the argument type is an object. JSON.stringify on the other hand returns JSON text, which can be converted back into a JSON object by using JSON.parse


As you might have noticed, while you tried (hopefully), calling .toString() which any object inherits (*) from Object.prototype.toString(), returns [object Object].

Thats how its defined internally, returning the internal [Class] name from an object. Of course, other objects can override this method (remember, its just originally defined on the prototype chain) and return pretty much anything.

JSON.stringify() on the other hand, is a method of the JSON object, which kind of serializes an object structure into a string version. Hence, Javascript Object Notation, it will describe an object with all nested structures in pure ascii string.


(*) exception: objects created with Object.create(null);


You can use the replacer and space parameter in JSON.stringify, passing the replacer argument as a function you can modify the object and space parameter helps you to give extra space before every key value pair.

const replacer = (key, value) => {
        // Filtering out properties
        if (typeof value === 'number') {
            return 1;
        }
        return value;
    },

    foo = {
        country: 'India',
        state: 'Gujarat',
        district: 45,
        cm: 'car',
        am: 7
    },

    result = JSON.stringify(foo, replacer);

console.log(result) // {"country":"India","state":"Gujarat","district":1,"cm":"car","am":1}

Space argument -

const obj = { a : 1, b:2};

const obj_str = JSON.stringify(obj, null, '     ');// '\t' gives one tab 

console.log(obj_str)

For more details you can visit this link.