admin管理员组

文章数量:1327692

Tested using chrome Canary

I can convert a date to JSON:

> (new Date()).toJSON()
  "2012-05-03T22:27:30.530Z"

I can convert it back to a Date:

> typeof (new Date("2012-05-03T22:27:30.530Z"))
  object

Why can't I parse it as a Date using JSON.parse()? JSON.parse returns a string, not a Date:

> JSON.parse('{"DateValue":"2012-05-03T22:27:30.530Z"}').DateValue
 "2012-05-03T22:27:30.530Z"

Tested using chrome Canary

I can convert a date to JSON:

> (new Date()).toJSON()
  "2012-05-03T22:27:30.530Z"

I can convert it back to a Date:

> typeof (new Date("2012-05-03T22:27:30.530Z"))
  object

Why can't I parse it as a Date using JSON.parse()? JSON.parse returns a string, not a Date:

> JSON.parse('{"DateValue":"2012-05-03T22:27:30.530Z"}').DateValue
 "2012-05-03T22:27:30.530Z"
Share edited May 3, 2012 at 22:54 Sylvain asked May 3, 2012 at 22:40 SylvainSylvain 19.3k26 gold badges102 silver badges146 bronze badges 1
  • Why would you expect it to return a Date object, if the value associated with "DateValue" key is not a Date object? – Imp Commented May 3, 2012 at 22:42
Add a ment  | 

3 Answers 3

Reset to default 8

Because a Date is not a valid type in JSON. JSON only knows about strings, numbers, booleans, arrays, and generic objects (associative arrays/hashes/maps/dictionaries/pick-your-favorite-name). When you convert anything else to JSON, you get one of the above - which means if you want to get the "something else" back out as the type it started as, the receiver has to do some extra work to recreate it.

There are JSON libraries that abstract that work away, and include an extra attribute indicating what class something is, so if the receiver is using the same library they'll get that type back, but that's still the same work, just hidden by the library.

Because in the JSON, the date is a string, in the same way new Date("2012-05-03T22:27:30.530Z") parses a string. You're expecting JavaScript to know that the string in the JSON is a date.

You need to pass the JSON parsed string to the date object to get a date back out:

var date = new Date(JSON.parse('{"DateValue":"2012-05-03T22:27:30.530Z"}').DateValue);

The .toJSON method is only there to return a value that can be representated in JSON. Yet JSON does not know about data types, and is not possible to store object instance information (like the prototype) in a JSON string.

So, the toJSON method of Date could return a number (e.g. the Unix timestamp), a plain object with properties representing year, month, day etc. (not so good because not parsable with the Date constructor) or - what happens to be - a string, in here the ISO time format. With that, you can use new Date(JSON.parse(stringified_date)) to create a new Date object.

If you would delete Date.prototype.toJSON;, JSON.stringify(new Date) would result in "{}".

本文标签: javascriptWhy can39t JSONparse() parse what datetoJSON() createsStack Overflow