简体   繁体   中英

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

ie 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM