jsonlite icon indicating copy to clipboard operation
jsonlite copied to clipboard

Add hms/difftime method

Open jeroen opened this issue 7 years ago • 2 comments

These are becoming common now in the tidyverse.

jeroen avatar Jul 19 '17 13:07 jeroen

It looks like there is a asJSON difftime file but it doesn't seem to be complete:

toJSON(difftime(Sys.time() + 180, Sys.time()))
## Error: No method asJSON S3 class: difftime

toJSON(hms("08 30 45"))
## [45]

Right now this is a breaking issue when trying to view data in vscode, their future workaround is to use force = TRUE.

mkoohafkan avatar Nov 08 '21 21:11 mkoohafkan

How about

setMethod("asJSON", "difftime", function(x, hms = c("string", "secs"), ...) {
  hms <- match.arg(hms)
  output = switch(hms,
                  string = paste(as.numeric(x, units = attr(x, "units")),
                    attr(x, "units")),
                  secs  = as.numeric(x, units = "secs")
  )
  output[is.na(x)] <- NA
  asJSON(output, ...)
})
toJSON(x)              
## [1] "[\"1.5 mins\",\"3 mins\",\"4.5 mins\",null]"
toJSON(x, hms = "secs")
## [1] "[90,180,270,\"NA\"]"

mkoohafkan avatar Nov 17 '21 07:11 mkoohafkan