Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify extra quotes

Consider:

var d = new Date();
var j = d.toJSON();
var s = JSON.stringify(d);

console.log for each of the variables returns:

Tue Jul 29 2014 13:27:19 GMT+0200 (W. Europe Summer Time)
2014-07-29T11:27:19.253Z // a string
"2014-07-29T11:27:19.253Z" // same string as above but packed in ""

I expected them to return the same thing, but then I read

http://www.json.org/js.html:

If the stringify method sees an object that contains a toJSON method, it calls that method, and stringifies the value returned. This allows an object to determine its own JSON representation.

and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify:

If an object being stringified has a property named toJSON whose value is a function, then the toJSON method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON method when called will be serialized. For example:

Does this mean that I always have to do something like:

var d = new Date();
var j = d.toJSON();
var s;

if (d.toJSON) {
    s = d.toJSON();
} else {
    s = JSON.stringify(d);
}

to ensure that s == j, since I can't rely on JSON.stringify not performing two serialisations?

EDIT

In light of jgillich's answer, the following code helps clarify things (for me at least):

var s = "xxx"
s = JSON.stringify(s)
s = JSON.stringify(s)
s = JSON.stringify(s)
s = JSON.stringify(s)
s = JSON.stringify(s)
console.log(s)

returns:

""\"\\\"\\\\\\\"\\\\\\\\\\\\\\\"xxx\\\\\\\\\\\\\\\"\\\\\\\"\\\"\"""

i.e. JSON.stringify returns not a string representation but rather a serialisation of an object. You'd think I'd realise that from the name and the presence of toString.

like image 602
Matt Jacobsen Avatar asked Jul 29 '14 11:07

Matt Jacobsen


People also ask

What is JSON stringify() method?

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 stringify in ajax?

stringify() method converts JavaScript objects into strings.

How to stringify function JavaScript?

Stringify a JavaScript ObjectUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.


1 Answers

toJSON() is not a function that is meant to return JSON. Instead, it is a function that, when it exists, is called before the JSON serialization happens. The following are exactly the same:

JSON.stringify(new Date().toJSON()); // toJSON called manually
JSON.stringify(new Date()); // toJSON called by the serializer
like image 178
jgillich Avatar answered Nov 16 '22 12:11

jgillich