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

Javascript

Javascript Problem Overview


In both the cases I get in output the content of the object:

alert(JSON.stringify(obj));

or

alert(obj.toString());

so... what's the difference? what are the advantages or disadvantages of each one?

Are there practical examples to show the difference?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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);

Solution 4 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1883212View Question on Stackoverflow
Solution 1 - JavascriptEsailijaView Answer on Stackoverflow
Solution 2 - JavascriptJacob GeorgeView Answer on Stackoverflow
Solution 3 - JavascriptjAndyView Answer on Stackoverflow
Solution 4 - JavascriptNayan PatelView Answer on Stackoverflow