【问题标题】:How do I pull .js or .json data from a specific URL into an R data frame如何将 .js 或 .json 数据从特定 URL 提取到 R 数据框中
【发布时间】:2023-04-04 04:29:01
【问题描述】:

我一直在尝试使用 RJSONIO 从这个特定的 URL:http://leafletjs.com/examples/us-states.js 提取数据。我转到该 URL 并通过按 CTRL+A 选择那里的所有数据来保存数据,然后将其粘贴到 notepad++ 中,将其保存为 test.json。从那时起,这是我在 R 中尝试过的:

library(RJSONIO)
json_file <- dir("test.json")
jsonIntoR <- fromJSON(readLines(json_file)[1])

我收到以下错误:

Error in fromJSON(readLines(json_file)[1]) : 
    error in evaluating the argument 'content' in selecting a method for function 'fromJSON': Error in file(con, "r") : invalid 'description' argument

我想将此 URL 中的数据转换为数据框,但无法克服此错误。我已尝试在此链接上使用该解决方案:Import JSON file from URL into R 但它对我不起作用。感谢您的帮助。

【问题讨论】:

    标签: json r rjsonio


    【解决方案1】:

    不要使用readLines(...)

    library(rjson)
    library(httr)
    url <- "http://leafletjs.com/examples/us-states.js"
    text <- content(GET(url),type="text")
    text <- sub("var statesData = ","",text)
    text <- sub(";$","",text)
    json <- fromJSON(text)
    

    您的文件实际上是 javascript,因此要使其可解释为 json,您需要去掉前导 var statesData = 和尾随 ;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多