从JSON文件导入数据到R

187

有没有一种方法可以将JSON文件中的数据导入到R中?更具体地说,该文件是一个由具有字符串、对象和数组字段的JSON对象数组组成的数组。 RJSON包对于如何处理这种情况不是非常清楚。参考http://cran.r-project.org/web/packages/rjson/rjson.pdf.


还有一个类似的问题:https://dev59.com/dkvSa4cB1Zd3GeqPivcP。 - Shane
嗨,Shane,我尝试使用RJSON。我主要对必要的数据操作感兴趣。这是我正在处理的JSON文件的示例。example.json:[{"winner":"68694999","votes":[{"ts":"Thu Mar 25 03:13:01 UTC 2010","user":{"name":"Lamur","user_id":"68694999"}},{"ts":"Thu Mar 25 03:13:08 UTC 2010","user":{"name":"Lamur","user_id":"68694999"}}],"lastVote":{"timestamp":1269486788526,"user":{"name":"Lamur","user_id":"68694999"}},"startPrice":0},...] - user313967
1
注意:如果JSON文件真的很大,似乎.so或.dll库无法处理它。更好的格式是NetCDF,但有些组织可能不知道这个问题。 - user1544219
7个回答

208

先安装rjson包:

install.packages("rjson")

那么:

library("rjson")
json_file <- "http://api.worldbank.org/country?per_page=10&region=OED&lendingtype=LNX&format=json"
json_data <- fromJSON(paste(readLines(json_file), collapse=""))

更新:自版本0.2.1以来

json_data <- fromJSON(file=json_file)

3
请注意,这次编辑指的是库的更新,而不是 R 本身。更新更改了上一个示例的最后一行,您仍然需要像上面那样加载库。 - Steven Waterman

110

jsonlite 将 JSON 导入到数据框中。它可以选择性地展开嵌套对象,嵌套数组将成为数据框。

> library(jsonlite)
> winners <- fromJSON("winners.json", flatten=TRUE)
> colnames(winners)
[1] "winner" "votes" "startPrice" "lastVote.timestamp" "lastVote.user.name" "lastVote.user.user_id"
> winners[,c("winner","startPrice","lastVote.user.name")]
    winner startPrice lastVote.user.name
1 68694999          0              Lamur
> winners[,c("votes")]
[[1]]
                            ts user.name user.user_id
1 Thu Mar 25 03:13:01 UTC 2010     Lamur     68694999
2 Thu Mar 25 03:13:08 UTC 2010     Lamur     68694999

1
当筛选结果时,使用数据框比列表更容易! - MS Berends

32

另外一个替代的包是RJSONIO。要转换一个嵌套列表,可以使用lapply函数:

l <- fromJSON('[{"winner":"68694999",  "votes":[ 
   {"ts":"Thu Mar 25 03:13:01 UTC 2010", "user":{"name":"Lamur","user_id":"68694999"}},   
   {"ts":"Thu Mar 25 03:13:08 UTC 2010", "user":{"name":"Lamur","user_id":"68694999"}}],   
  "lastVote":{"timestamp":1269486788526,"user":
   {"name":"Lamur","user_id":"68694999"}},"startPrice":0}]'
)
m <- lapply(
    l[[1]]$votes, 
    function(x) c(x$user['name'], x$user['user_id'], x['ts'])
)
m <- do.call(rbind, m)

提供有关您示例中投票的信息。


1
x$user$name, x$user$user_id 应该改为 x$user['name'], x$user['user_id']。此外,m <- do.call(rbind, m) 可能是将列表转换为矩阵的更好方法。 - jbaums
有没有类似于XML包中的convertToDataFrame函数的JSON函数? - userJT

16

如果URL是https,例如Amazon S3所使用的,则使用getURL函数

json <- fromJSON(getURL('https://s3.amazonaws.com/bucket/my.json'))

11
提示:getURL在RCurl包中。 - Mark McDonald
1
同时,Error in function (type, msg, asError = TRUE) : Protocol "s3" not supported or disabled in libcurl - d8aninja

4

首先安装RJSONIO和RCurl包:

install.packages("RJSONIO")
install.packages("(RCurl")

在控制台中使用RJSONIO尝试以下代码

library(RJSONIO)
library(RCurl)
json_file = getURL("https://raw.githubusercontent.com/isrini/SI_IS607/master/books.json")
json_file2 = RJSONIO::fromJSON(json_file)
head(json_file2)


3

加载包:

library(httr)
library(jsonlite)

我在将JSON转换为数据帧/CSV时遇到了问题。对于我的情况,我执行了以下操作:

Token <- "245432532532"
source <- "http://......."
header_type <- "applcation/json"
full_token <- paste0("Bearer ", Token)
response <- GET(n_source, add_headers(Authorization = full_token, Accept = h_type), timeout(120), verbose())
text_json <- content(response, type = 'text', encoding = "UTF-8")
jfile <- fromJSON(text_json)
df <- as.data.frame(jfile)

然后从df转换为csv格式。

如果需要,这种格式使得将其转换为多个.csv文件变得容易。

重要的是,content函数应该具有type =“text”


1

导入httr包

library(httr)

获取URL
url <- "http://www.omdbapi.com/?apikey=72bc447a&t=Annie+Hall&y=&plot=short&r=json"
resp <- GET(url)

打印resp的内容作为文本。
content(resp, as = "text")

打印resp的内容

content(resp)

使用content()获取resp的内容,但这次不要指定第二个参数。R会自动识别你正在处理JSON,并将JSON转换为命名的R列表。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接