jsonlite icon indicating copy to clipboard operation
jsonlite copied to clipboard

auto_unbox = T destroyed by POSIXt = 'mongo' in toJSON()

Open nabudaldah opened this issue 7 years ago • 3 comments

When doing:

toJSON(list(t = Sys.time()), POSIXt = 'mongo', auto_unbox = T)

I expected:

{"t":{"$date":1501530029411}}

But I get:

{"t":[{"$date":1501530029411}]}

Workaround by using unbox() directly:

toJSON(list(t = unbox(Sys.time())), POSIXt = 'mongo', auto_unbox = T)

nabudaldah avatar Jul 31 '17 19:07 nabudaldah

Same issue here #192

it seems a bug in automatic conversion to mongo timestamp

jsonlite::toJSON(list("t" = list("$date" = 1501530029411)),auto_unbox = T)
# {"t":{"$date":1501530029411}} 
jsonlite::toJSON(list("t" = list(list("$date" = 1501530029411))),auto_unbox = T)
#  {"t":[{"$date":1501530029411}]} 

Your workaround converts to scalar, so it works and at the moment i guess we have only these two solutions: unbox or direct list wrapper with $date

Note for unbox : it can be used with atomic vectors of length 1 or data frames with 1 row

So it works with

t1 <- Sys.time()
#  "2017-12-28 11:17:53 CET"

jsonlite::unbox(t1)
#  "2017-12-28 11:17:53"

jsonlite::toJSON(list("t" = jsonlite::unbox(t1)), POSIXt = 'mongo', auto_unbox = T)
#  {"t":{"$date":1514456273863}} 

But it shows an error with

t2 <- as.POSIXct( as.numeric(t1),tz = "CET",origin = "1970-01-01")
#  "2017-12-28 11:17:53 CET"

jsonlite::unbox(t2)
#  Error: Only atomic vectors of length 1 or data frames with 1 row can be unboxed.

This is due to the attribute $tzone

attributes(t2)
#  $class
#  "POSIXct" "POSIXt" 

# $tzone
#  "CET"

# removing attribute
attr(t2,"tzone") <- NULL

jsonlite::unbox(t2)
#  "2017-12-28 11:17:53" #OK

jsonlite::toJSON(list("t" = jsonlite::unbox(t2)), POSIXt = 'mongo', auto_unbox = T)
#  {"t":{"$date":1514456273863}} 

maxto avatar Dec 28 '17 09:12 maxto

Maybe the same as https://github.com/jeroen/mongolite/issues/198 ...

jeroen avatar Apr 13 '20 18:04 jeroen

But it shows an error with

t2 <- as.POSIXct( as.numeric(t1),tz = "CET",origin = "1970-01-01")
#  "2017-12-28 11:17:53 CET"

jsonlite::unbox(t2)
#  Error: Only atomic vectors of length 1 or data frames with 1 row can be unboxed.

This is due to the attribute $tzone

attributes(t2)
#  $class
#  "POSIXct" "POSIXt" 

# $tzone
#  "CET"

# removing attribute
attr(t2,"tzone") <- NULL

jsonlite::unbox(t2)
#  "2017-12-28 11:17:53" #OK

jsonlite::toJSON(list("t" = jsonlite::unbox(t2)), POSIXt = 'mongo', auto_unbox = T)
#  {"t":{"$date":1514456273863}} 

This does not work if the tzone attribute is not your current time zone, as removing the tzone attribute modifies the time value. Any other suggestion how to deal with that case?

bguillod avatar May 27 '20 08:05 bguillod