[json] JSON 파일에서 R로 데이터 가져 오기

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&region=OED&lendingtype=LNX&format=json"
json_data <- fromJSON(paste(readLines(json_file), collapse=""))

업데이트 : 버전 0.2.1 이후

json_data <- fromJSON(file=json_file)


답변

jsonliteJSON을 데이터 프레임으로 가져옵니다. 선택적으로 중첩 된 객체를 평평하게 할 수 있습니다. 중첩 배열은 데이터 프레임이됩니다.

> 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)

귀하의 예에서 투표에 대한 정보를 제공합니다.


답변

Amazon S3에 사용 된 URL이 https 인 경우 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)


답변

패키지 :

  • 도서관 (httr)
  • 도서관 (jsonlite)

json을 dataframe / 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'입니다.


답변

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)

resp의 내용을 얻으려면 content ()를 사용하십시오. 그러나 이번에는 두 번째 인수를 지정하지 않습니다. R은 자동으로 JSON을 처리하고 있음을 파악하고 JSON을 명명 된 R 목록으로 변환합니다.