I have the following R data frame:
Values
Type1 123
Type2 4565
Type3 7812
I expect the JSON output to be
{"Type1":123, "Type2":4565, "Type3":7812}
The number field can w/wo quote
I used jsonlite toJSON, the output is:
[{"Values":123,"_row":"Type1"},
{"Values": 4565,"_row":"Type2"},
{"Values": 7812,"_row":"Type3"}]
Solution using rjson:
df <- data.frame(Values = c(123, 4565, 7812))
rownames(df) <- paste0("Type", 1:3)
library(rjson)
toJSON(setNames(df$Values, rownames(df)))
[1] "{\"Type1\":123,\"Type2\":4565,\"Type3\":7812}"
jsonlite is actually preserving your data structure, i.e., keeping your rownames (Type1, Type2, Type3).
Anyway, using jsonlite you could get the same behaviour with:
> jsonlite::toJSON(df %>% t() %>% tibble::as_data_frame())
[{"Type1":123,"Type2":4565,"Type3":7812}]
Please realize that with this solution you will lose the original column name Values. If the row names are important but not the column name, you should think about defining your data in a different way, as dealing with rownames can get messy. You can add the Type as a second column or transpose your data -- one row, as many columns as types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With