从JSON文件导入数据到R
有没有办法将数据从JSON文件导入到R?更具体地说,该文件是包含字符串字段,对象和数组的JSON对象的数组。 RJSON软件包不清楚如何处理http://cran.r-project.org/web/packages/rjson/rjson.pdf。从JSON文件导入数据到R
首先安装rjson
包:
install.packages("rjson")
然后:
library("rjson")
json_file <- "http://api.worldbank.org/country?per_page=10®ion=OED&lendingtype=LNX&format=json"
json_data <- fromJSON(paste(readLines(json_file), collapse=""))
更新:自版本0.2.1
json_data <- fromJSON(file=json_file)
另一种包装是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)
在您的示例中给出了有关投票的信息。
如果URL是HTTPS,像用于亚马逊S3中,然后用的getURL
json <- fromJSON(getURL('https://s3.amazonaws.com/bucket/my.json'))
PSA:getURL在RCurl pacakge中。 – 2015-03-05 04:57:52
此外,函数中的错误(type,msg,asError = TRUE): 协议“s3”在libcurl中不受支持或禁用 – d8aninja 2017-08-30 19:05:43
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
我喜欢这个答案和库比接受的更多 – 2016-03-06 05:58:12
首先安装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)
Duplicate:http://stackoverflow.com/questions/2061897/parse-json-with-r。如果你有一个特定的数据例子,这将有所帮助。否则,rjson可以做你所需要的,以及数据操作(例如使用apply函数或plyr)。 – Shane 2010-04-11 16:37:37
也类似于这个问题:http://stackoverflow.com/questions/2260147/transposing-json-list-of-dictionaries-for-analysis-in-r。 – Shane 2010-04-11 16:39:16
嗨谢恩,尝试使用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 “:{” 时间戳 “:1269486788526,” 用户 “:{” 名称 “:” Lamur”, “USER_ID”: “68694999”}}, “startPrice”:0},... ] – user313967 2010-04-11 17:01:37