0

我是 R 的初学者。我的情况是我有一个带有嵌套数组的 JSON 数据集。在 JSON 文件中,一个机构如下所示:

{
    "website": "www.123.org",
    "programs": [
        {
            "website": "www.111.com",
            "contact": "Jim"
        },
        {
            "website": "www.222.com",
            "contact": "Han"
        }
    ]
}

对于每个机构,可能有一个项目或更多项目。我在 JSON 中有 100 多个机构和近两百个程序。我想为每个机构添加 id 并为每个程序添加 idpr。最后,我希望我能得到一个如下所示的 data.frame:

id idpr website     websitepr   contactpr
1  1    www.123.org www.111.com Jim
1  2    www.123.org www.222.com Han
2  1    www.345.org www.aaa.com Lily
3  1    www.567.org www.bbb.com Jack
3  2    www.567.org www.ccc.com Mike
3  3    www.567.org www.ddd.com Minnie
.........

我试着写一个这样的嵌套循环: count<-0 for (n in json_data){ count<-count+1 id<-c(id,count) website<-c(website,n$website) countpr<- 1 for (i in n$programs){ id<-c(id,count) website<-c(website,n$website) idpr<-c(idpr,countpr) websitepr<-c(websitepr,i$website) contactpr<-c(contactpr,i$contact) countpr<-countpr+1 } } 但是这个嵌套循环不能给我想要的结果。谢谢你帮助我!

4

2 回答 2

0

你可以写一个类网站{

//全部写入数据成员

//程序作为类程序的对象

}

并使用jackson api将其转换为字符串。使用 Mapper.writeValueAsString(网站对象)

需要的 jar 是 1.jackson-core-2.0.2.jar

  1. 杰克逊-数据绑定-2.0.2.jar。
于 2013-10-10T15:00:04.043 回答
0

试试这个:

# sample data
json.file <- textConnection('[{"website":"www.123.org","programs":[{"website":"www.111.com","contact":"Jim"},{"website":"www.222.com","contact":"Han"}]},{"website":"www.345.org","programs":[{"website":"www.aaa.com","contact":"Lily"}]},{"website":"www.567.org","programs":[{"website":"www.bbb.com","contact":"Jack"},{"website":"www.ccc.com","contact":"Mike"},{"website":"www.ddd.com","contact":"Minnie"}]}]')

# read the data into an R nested list
library(rjson)
raw.data <- fromJSON(file = json.file)

# a function that will process one institution
process.one <- function(id, institution) {
   website   <- institution$website
   websitepr <- sapply(institution$programs, `[[`, "website")
   contactpr <- sapply(institution$programs, `[[`, "contact")
   data.frame(id, idpr = seq_along(websitepr),
              website, websitepr, contactpr)
}

# run the function on all institutions and put the pieces together
do.call(rbind, Map(process.one, seq_along(raw.data), raw.data))
#   id idpr     website   websitepr contactpr
# 1  1    1 www.123.org www.111.com       Jim
# 2  1    2 www.123.org www.222.com       Han
# 3  2    1 www.345.org www.aaa.com      Lily
# 4  3    1 www.567.org www.bbb.com      Jack
# 5  3    2 www.567.org www.ccc.com      Mike
# 6  3    3 www.567.org www.ddd.com    Minnie
于 2013-10-10T15:28:55.250 回答