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?
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.
JSON. parse() is used to convert String to Object. JSON. stringify() is used to convert Object to String.
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.
stringify() is the opposite of JSON. parse(), which converts JSON into Javascript objects.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With