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"}]
nicola
  • 24,005
  • 3
  • 35
  • 56
BlueDolphin
  • 9,765
  • 20
  • 59
  • 74

2 Answers2

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}"
pogibas
  • 27,303
  • 19
  • 84
  • 117
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.

quartin
  • 431
  • 7
  • 9