簡體   English   中英

使用行名和列名將R數據幀轉換為JSON

[英]Convert R dataframe to JSON using row names and column names

考慮以下簡單的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"}
}

任何想法如何去做?

在這些情況下,有時候從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"

所以,現在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM