jeroen / jsonlite

A Robust, High Performance JSON Parser and Generator for R
http://arxiv.org/abs/1403.2805
Other
376 stars 40 forks source link

fromJSON doesn't accept ISO8601 Dates #227

Closed phabee closed 6 years ago

phabee commented 6 years ago

Hi there

Handling ISO8601 Datetime Objects works fine when writing JSONs from R-Objects using the parameters Date and POSIXt:

  json_string <- jsonlite::toJSON(vrp_model, pretty = TRUE, digits = NA,
                                  factor = "string", **Date** = "ISO8601", **POSIXt** = "ISO8601")

However, the parameter don't seem to be available on the fromJSON method (which is also what is expected when reading the help). The following command

model <- jsonlite::fromJSON(path2file, Date = "ISO8601", POSIXt = "ISO8601")

would end up with the error:

Error in simplify(obj, simplifyVector = simplifyVector, simplifyDataFrame = simplifyDataFrame, : unused arguments (Date = "ISO8601", POSIXt = "ISO8601")

So as it seems to me, there's no way to load JSONs having ISO8601-Datetime Objects. If there are, the time will not be captured, since as.POSIXct fails to do it. I have a JSON with datetime values of the following kind: "2017-10-10T06:00:00". When trying to import, the time is truncated.

It would be great, if one could pass the mentioned arguments as well on the fromJSON-method.

Kind regards Fabian

jeroen commented 6 years ago

JSON doesn't support dates. If you export dates to ISO strings, there is no way for jsonlite to convert these back to dates.

Try using POSIXt = "mongo" in toJSON that may be a bette fit.

phabee commented 6 years ago

Sorry, I don't quite get that. I think JSON is a textbased format and when I provide date-format to the toJSON method then I would expect that the fromJSON method could manage to convert Strings back to i.e. datetime objects. Am I wrong?

jeroen commented 6 years ago

Yes you are wrong. Once the date is converted to a string, it is no longer a date. It's just a string. There is no magical way that the json reader can recognize the string as being a date.

jeroen commented 6 years ago

No because the deserializer doesn't know the string is a date. You lost that information by converting it into a string. A string can contain anything: it may be a date, it may be a name of an elephant.

The deserializer just finds a string. If you (the user) know that a particular string contains a date, you can convert it in your code with as.Date() or as.POSIXct().

phabee commented 6 years ago

Cool. Thanks a lot. Now I'm with you.