Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"}]
like image 988
BlueDolphin Avatar asked Sep 21 '17 18:09

BlueDolphin


Video Answer


2 Answers

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}"
like image 170
pogibas Avatar answered Nov 02 '22 07:11

pogibas


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.

like image 37
quartin Avatar answered Nov 02 '22 08:11

quartin