programing

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

starjava 2023. 3. 8. 20:33
반응형

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

JSON 파일에서 R로 데이터를 Import하는 방법이 있습니까?구체적으로는 문자열 필드, 개체 및 배열이 포함된 JSON 개체 배열입니다.RJSON 패키지는 이 http://cran.r-project.org/web/packages/rjson/rjson.pdf의 대처 방법에 대해 명확하지 않습니다.

먼저 패키지를 설치합니다.

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)

jsonlite는 JSON을 데이터 프레임으로 Import합니다.옵션으로 중첩된 개체를 평평하게 만들 수 있습니다.중첩된 배열은 데이터 프레임이 됩니다.

> 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입니다.중첩 목록을 변환하려면 래플리를 사용하면 다음 작업을 수행할 수 있습니다.

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이 Amazon S3에서 사용되는 것처럼https일 경우 get을 사용합니다.URL

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)

패키지를 로드합니다.

library(httr)
library(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 패키지 Import

library(httr)

URL 가져오기

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

응답 내용을 텍스트로 인쇄합니다.

content(resp, as = "text")

응답 내용 인쇄

content(resp)

content()를 사용하여 응답 내용을 가져오지만 두 번째 인수는 지정하지 않습니다.R은 JSON과 거래하고 있음을 자동으로 인식하고 JSON을 이름 있는 R 목록으로 변환합니다.

언급URL : https://stackoverflow.com/questions/2617600/importing-data-from-a-json-file-into-r

반응형