[英]Convert R dataframe to JSON using row names and column names
Consider the following simple R data frame: 考虑以下简单的R数据帧:
shape1 <- c('red','triangle')
shape2 <- c('blue','circle')
df <- data.frame(shape1,shape2)
rownames(df) <- c('Prop1','Prop2')
I would like to convert it to the following JSON: 我想将其转换为以下JSON:
{
"shape1": {"Prop1":"red","Prop2":"triangle"},
"shape2": {"Prop1":"blue","Prop2":"circle"}
}
Any ideas how to go about this? 任何想法如何去做?
In these situations it's sometimes easier to work backwards from the JSON and find out what R structure is required, to then give you back that JSON. 在这些情况下,有时候从JSON向后进行工作并找出所需的R结构,然后将其返回给您,会更容易。
## 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"
So now lst
is the structure you require to get to your desired JSON 所以,现在lst
是你需要得到您想要的JSON结构
jsonlite::toJSON(lst, pretty = T)
# {
# "shape1": {
# "Prop1": ["red"],
# "Prop2": ["triangle"]
# },
# "shape2": {
# "Prop1": ["blue"],
# "Prop2": ["circle"]
# }
# }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.