Thursday, December 15, 2016

Difference between toString() and JSON.stringify()

["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


@reference_1_stackoverflow
@reference_2_mozilla

No comments:

Post a Comment