jsonlite icon indicating copy to clipboard operation
jsonlite copied to clipboard

Option for toJSON() to output a decimal point for all doubles

Open torfason opened this issue 1 year ago • 0 comments

The fromJSON() function takes care to treat 1 as an integer and 1.0 as a double, which is great. However, it seems that toJSON() does not make this distinction. This means that a double 1.0 gets converted to an integer on a json roundtrip. If there was an option to make toJSON() distinguish between the two cases this would increase the number of objects that can be represented with fidelity in json. Below is a reprex to demonstrate the issue:

# Define list with 1 as integer and double
l <- list(a = 1L, b = 1.0, c = 1.1)
l |> str()
#> List of 3
#>  $ a: int 1
#>  $ b: num 1
#>  $ c: num 1.1

# toJSON does not distinguish integers from integerish doubles 
j <- jsonlite::toJSON(l, pretty = TRUE)
j
#> {
#>   "a": [1],
#>   "b": [1],
#>   "c": [1.1]
#> }
waldo::compare(l, jsonlite::fromJSON(j))
#> `old$b` is a double vector (1)
#> `new$b` is an integer vector (1)
j_manual <- '{
  "a": [1],
  "b": [1.0],
  "c": [1.1]
}'
# fromJSON(), however, does distinguish integers from doubles
waldo::compare(l, jsonlite::fromJSON(j_manual))
#> ✔ No differences

If there is such an option, I apologize for submitting an issue.

torfason avatar Mar 21 '24 21:03 torfason