R:jsonlite - 导出键:列表列表中的值对

时间:2016-03-25 21:03:48

标签: json r

我有一个长度可变的列表。每个嵌套列表的第一个值是键,列表中的其余值将是数组条目。它看起来像这样:

[[1]]
[1] "Bob"      "Apple"

[[2]]
[1] "Cindy"    "Apple"     "Banana"      "Orange"   "Pear"   "Raspberry"         

[[3]]
[1] "Mary"     "Orange"    "Strawberry"

[[4]]
[1] "George"   "Banana"

我已按如下方式提取了密钥和条目:

keys <- lapply(x, '[', 1)
entries <- lapply(x, '[', -1)

但是现在我有了这些,我不知道如何在R中关联一个键:值对而不先创建矩阵,但这很愚蠢,因为我的数据无论如何都不适合矩形(每个例子)我见过使用矩阵中的列名作为键值。)

这是我使用矩阵,分配rownames,然后使用jsonLite导出到JSON的糟糕方法。

#Create a matrix from entries, without recycling
#I found this function on StackOverflow which seems to work...
cbind.fill <- function(...){
  nm <- list(...) 
  nm <- lapply(nm, as.matrix)
  n <- max(sapply(nm, nrow)) 
  do.call(cbind, lapply(nm, function (x) 
    rbind(x, matrix(, n-nrow(x), ncol(x))))) 
}
#Call said function
matrix <- cbind.fill(entries)
#Transpose the thing
matrix <- t(matrix)
#Set column names
colnames(matrix) <- keys
#Export to json
json<-toJSON(matrix)

结果很好,但实施很糟糕。结果:

[{"Bob":["Apple"],"Cindy":["Apple","Banana","Orange","Pear","Raspberry"],"Mary":["Orange","Strawberry"],"George":["Banana"]}]

请让我知道可能有更好的方法来实现这一目标。

3 个答案:

答案 0 :(得分:1)

考虑以下lapply()方法:

library(jsonlite)
entries <- list(c('Bob', 'Apple'),
                c('Cindy', 'Apple', 'Banana', 'Orange','Pear','Raspberry'),
                c('Mary', 'Orange', 'Strawberry'),
                c('George', 'Banana'))

# ITERATE ALL CONTENTS EXCEPT FIRST
inner <- list()
nestlist <- lapply(entries, 
                          function(i) {
                          inner <- i[2:length(i)]
                          return(inner)
                   })

# NAME EACH ELEMENT WITH FIRST ELEMENT
names(nestlist) <- lapply(entries, function(i) i[1])
#$Bob
#[1] "Apple"    
#$Cindy
#[1] "Apple"     "Banana"    "Orange"    "Pear"      "Raspberry"    
#$Mary
#[1] "Orange"     "Strawberry"    
#$George
#[1] "Banana"

x <- toJSON(list(nestlist), pretty=TRUE)
x
#[
#  {
#    "Bob": ["Apple"],
#    "Cindy": ["Apple", "Banana", "Orange", "Pear", "Raspberry"],
#    "Mary": ["Orange", "Strawberry"],
#    "George": ["Banana"]
#  }
#] 

答案 1 :(得分:1)

怎么样:

names(entries) <- unlist(keys) 
toJSON(entries)

答案 2 :(得分:0)

我认为这已经得到了充分的回答,但这是一种使用purrrjsonlite的方法。

library(purrr)
library(jsonlite)


sample_data <- list(
  list("Bob","Apple"),
  list("Cindy","Apple","Banana","Orange","Pear","Raspberry"),
  list("Mary","Orange","Strawberry"),
  list("George","Banana")
)

sample_data %>%
  map(~set_names(list(.x[-1]),.x[1])) %>%
  toJSON(auto_unbox=TRUE, pretty=TRUE)