使用行名称和列名称将R dataframe转换为JSON

时间:2017-02-08 20:33:15

标签: json r dataframe

考虑以下简单的R数据框:

shape1 <- c('red','triangle')
shape2 <- c('blue','circle')
df <- data.frame(shape1,shape2)
rownames(df) <- c('Prop1','Prop2')

我想将其转换为以下JSON:

{
"shape1": {"Prop1":"red","Prop2":"triangle"},
"shape2": {"Prop1":"blue","Prop2":"circle"}
}

任何想法如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

在这些情况下,有时更容易从JSON向后工作并找出需要什么R结构,然后再返回JSON。

## start with the desired json
js <- '{"shape1": {"Prop1":"red","Prop2":"triangle"},
"shape2": {"Prop1":"blue","Prop2":"circle"}}'

## convert it into an R object (in this case, it's a list)
lst <- jsonlite::fromJSON(js)
lst
# $shape1
# $shape1$Prop1
# [1] "red"
# 
# $shape1$Prop2
# [1] "triangle"
# 
# 
# $shape2
# $shape2$Prop1
# [1] "blue"
# 
# $shape2$Prop2
# [1] "circle"

所以现在lst是获得所需JSON所需的结构

jsonlite::toJSON(lst, pretty = T)
# {
#   "shape1": {
#       "Prop1": ["red"],
#       "Prop2": ["triangle"]
#   },
#   "shape2": {
#       "Prop1": ["blue"],
#       "Prop2": ["circle"]
#   }
# }