Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't JSON.parse() parse what date.toJSON() creates?

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"
like image 682
Sylvain Avatar asked Dec 21 '22 22:12

Sylvain


1 Answers

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.

like image 51
Mark Reed Avatar answered Mar 20 '23 00:03

Mark Reed