How to convert R dataframe to Json in name/value pair?
Asked Answered
P

2

6

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"}]
Perpetuity answered 21/9, 2017 at 18:8 Comment(2)
Seems different, in my case, the row names are dynamic.Perpetuity
Try toJSON(as.list(setNames(df$Values,rownames(df))),auto_unbox=TRUE).Gammadion
B
7

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}"
Betancourt answered 21/9, 2017 at 21:0 Comment(2)
Seems jsonlite drop the name in the same "toJSON" command. I will try to use rjson then.Perpetuity
BTW, the string can convert back to data frame using t(fromJSON("{\"Type1\":123,\"Type2\":4565,\"Type3\":7812}"))Perpetuity
S
2

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.

Statutable answered 25/9, 2017 at 19:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.