有没有办法从JSON文件为R导入数据?更具体而言,该文件是JSON对象与字符串字段,目的和数组的数组。该RJSON包不上如何处理这个http://cran.r-project.org/web/packages/rjson/rjson.pdf很清楚。
首先安装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)
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
一种替代包是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'))
首先安装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)
包:
我有问题,转换到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。
在这种格式应该很容易,如果需要将其转换为多个.csvs。
最重要的部分是内容的功能应该有type = 'text'
。
library(httr)
url <- "http://www.omdbapi.com/?apikey=72bc447a&t=Annie+Hall&y=&plot=short&r=json"
resp <- GET(url)
content(resp, as = "text")
content(resp)
使用内容()来获取RESP的内容,但这次不指定第二个参数。 [R自动计算出你所面对的是JSON,并转换JSON到一个名为[R列表。