JaimeCr JaimeCr - 2 months ago 12
JSON Question

Uniform conversion of numeric values to JSON

I'm trying to convert a data.table object to JSON. The columns, which have

numeric
values, should be converted to JSON values in an "uniform" way, i.e. all values should contain the decimal part, even if it's ".0". What I have is:

library(RJSONIO)
test <- data.table(V1 = c(1.0, 2.0, 4.5, 3.0))
cat(toJSON(test))

{
"V1": [ 1, 2, 4.5, 3 ]
}


However, what I'm trying to do is getting the following output:

{
"V1": [ 1.0, 2.0, 4.5, 3.0 ]
}


I've tried with other libraries such as
rjson
and I'm getting the same result. I can't seem to find any option that would control this. My last option would be to manually process the output the JSON string, adding the required ".0"s at the end, but I'm wondering if there is a better option. Any help would be greatly appreciated.

Answer

The following code does exactly what you want using format and round to specify the number of decimal places:

     library(RJSONIO)
     library(data.table)

     test <- data.table(V1 = c(1.0, 2.0, 4.5, 3.0))
     test$V1 <- format(round(test$V1, 2))
     cat(toJSON(test))

results :

{
 "V1": [ "1.0", "2.0", "4.5", "3.0" ] 
}