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

Asked

Viewed 5,954 times

5

var arr = [1,2,3];

arr.toString(); // "1,2,3"
JSON.stringify(arr); // "[1,2,3]"
  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.

2 answers

8

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

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

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

And 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 cannot.

5

  • toString returns the string representation of the object, in the case of the question, of an array
  • JSON.stringify converts a javascript value, in the case of an array question, to a JSON

If you just want to show the result on the page to the user, then it may not make a difference once the user perceives the information being 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 doesn’t happen anymore if you only have the text that comes out of toString because it’s not a JSON:

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

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

Already the toString is common to be used to obtain a text representation of the object in question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.