首页 文章

将数据从JSON文件导入R

提问于
浏览
138

有没有办法将数据从JSON文件导入R?更具体地说,该文件是具有字符串字段,对象和数组的JSON对象数组 . RJSON包关于如何处理这个http://cran.r-project.org/web/packages/rjson/rjson.pdf并不是很清楚 .

7 回答

  • 1

    包:

    • library(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' .

  • 71

    首先安装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起 Update:

    json_data <- fromJSON(file=json_file)
    
  • 15

    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
    
  • 161

    另一个包是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)
    

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

  • 29

    如果URL是https,就像用于Amazon S3一样,那么使用getURL

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

    First install the RJSONIO and RCurl package:

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

    Try below code using RJSONIO in console

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

    要导入,我必须添加“标记:

    json_data < - fromJSON(file =“json_file”)

    希望能帮助别人 .

    科马克

相关问题