What's the difference between using toString () and JSON.stringify ()?

3
var arr = [1,2,3];

arr.toString(); // "1,2,3"
JSON.stringify(arr); // "[1,2,3]"
    
asked by anonymous 02.10.2018 / 01:25

2 answers

6

JSON.stringify() is a function of the JSON object that will create a string of the object within the pattern adopted by JSON. By a near coincidence (not 100% because JSON is based on JS notation) the toString() method gives the same result at first.

If some object creates a specialized form of toString() the result can be another. JSON.stringify() needs more stability. The example already shows that it may be different.

One thing I say is that people use toString() wrong , they do not understand that they do not is a method to create a text shown the whole object, it can have very different results than expected and is common in many objects only show the name of the class, which has no use for almost anything other than debugging.

It is obvious that the fact that one is a function and another is a method is also different, the second can have a null object normally, the first can not.

    
02.10.2018 / 01:56
5
  • toString returns the string representation of the object, in the question, from an array
  • JSON.stringify converts a javascript value, in case of question an array, in a JSON

If you only want to show the result on the page to the user, then it can make no difference since the user perceives the information being in one way or another.

But remember that JSON is a data format, and if you have the JSON corresponding to the array, the [1,2,3] , you can rebuild the array using JSON.Parse :

console.log(JSON.parse("[1,2,3]"));

The same is no longer the case if you only have text that exits from toString because it is not a JSON:

console.log(JSON.parse("1,2,3"));

So you should use JSON.stringify when you want to get a JSON that represents the value it has, be it an object, an array, a date, and so on. This is common in exchange for information, such as sending and receiving values for API's.

While toString is common to be used to get a text representation of the object in question.

    
02.10.2018 / 01:54