RJSONIO
RJSONIO copied to clipboard
Respect options()$digits
The default digits = 5
in the S4 method for toJSON
(for numeric
) is pretty low. No doubt this keeps default output to a healthy size, but it's insufficient in some applications, like mapping. See, for example, https://github.com/jcheng5/leaflet-shiny/issues/13 and https://github.com/ramnathv/rCharts/issues/248.
Perhaps toJSON()
might allow for user-level specification of numeric precision, defaulting to options()$digits
instead of 5.
You can specify the number of digits:
library(RJSONIO) x = rnorm(4) toJSON(x) [1] "[ -0.5656, 1.0183, 0.79875, -0.30822 ]" toJSON(x, digits = 10) [1] "[ -0.5656030508, 1.018288136, 0.7987455911, -0.3082151828 ]"
Yes—and I would!—but I'm using libraries that don't allow it, like leaflet-shiny
and rCharts
(see the examples).
My workaround is to wrap values with the precision I need in a Decimal
class:
Decimal <- setClass("Decimal", slots = c(digits = "numeric"), contains = "numeric")
setMethod("toJSON", signature="Decimal", function (x, ...) toJSON(as.numeric(x), digits = x@digits, ...))
I just thought it might be reasonable to pull the default from somewhere instead of just having it be 5. But I can understand why changing that might break things.
I can add code to get the default value for the digits parameter from options(). However, the real issue is that the other packages should provide a way for you to control how the JSON is generated.
Hi David
I've pushed the minute change to compute the default value for the digits parameter from the options vector. This is fine and allows you to do what you want. However, I do strongly suggest you push the authors of the other packages to allow you to control the digits for the JSON output in their functions. Firstly, using options() is a global variable and this is bad programming practice. Secondly, propagating data with n digits when it is actually meaningful to only << n digits is very poor practice. If we measure a variable to 2 digits, but disseminate it to 7 is just bad!
FWIW shiny does this now, albeit through an option of our own: https://github.com/rstudio/shiny/blob/master/R/shiny.R#L35
Thanks. So it is now in both! However, rather than relying on global options for passing digits to implicit calls to toJSON(), it would be better to support specifying the arguments for toJSON() in the higher-level functions.
Great! Good to have it in RJSONIO too. Thanks @duncantl @jcheng5
On Jul 29, 2014, at 8:49 PM, Joe Cheng [email protected] wrote:
FWIW shiny does this now, albeit through an option of our own: https://github.com/rstudio/shiny/blob/master/R/shiny.R#L35
— Reply to this email directly or view it on GitHub.