jsonlite
jsonlite copied to clipboard
Add hms/difftime method
These are becoming common now in the tidyverse.
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
.
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\"]"