Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 288
user1883212 Avatar asked Apr 05 '13 12:04

user1883212


People also ask

What does JSON Stringify () do?

JSON.stringify() The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

What is the difference between JSON parse and JSON Stringify?

JSON. parse() is used to convert String to Object. JSON. stringify() is used to convert Object to String.

When should I use JSON Stringify?

The JSON. stringify() method in Javascript is used to create a JSON string out of it. While developing an application using JavaScript, many times it is needed to serialize the data to strings for storing the data into a database or for sending the data to an API or web server.

What is the opposite of JSON Stringify?

stringify() is the opposite of JSON. parse(), which converts JSON into Javascript objects.


2 Answers

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 
like image 85
Esailija Avatar answered Sep 22 '22 07:09

Esailija


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

like image 44
Jacob George Avatar answered Sep 19 '22 07:09

Jacob George