成功将分页JSON对象强制转换为R数据帧

ver*_*his 6 r httr jsonlite

我试图将从API中提取的JSON转换为R中的数据帧,以便我可以使用和分析数据.

#Install needed packages
require(RJSONIO)
require(httr)

#request a list of companies currently fundraising using httr
r <- GET("https://api.angel.co/1/startups?filter=raising")
#convert to text object using httr
raise <- content(r, as="text")
#convert to list using RJSONIO
fromJSON(raise) -> new
Run Code Online (Sandbox Code Playgroud)

一旦我得到这个对象,new我就很难将列表解析成数据帧.json有这样的结构:

{
  "startups": [
 {
  "id": 6702,
  "name": "AngelList",
  "quality": 10,
  "...": "...",
  "fundraising": {
    "round_opened_at": "2013-07-30",
    "raising_amount": 1000000,
    "pre_money_valuation": 2000000,
    "discount": null,
    "equity_basis": "equity",
    "updated_at": "2013-07-30T08:14:40Z",
    "raised_amount": 0.0
      }
    }
  ],
  "total": 4268 ,
  "per_page": 50,
  "page": 1,
  "last_page": 86
}
Run Code Online (Sandbox Code Playgroud)

我已尝试new使用以下代码查看各个元素:

 new$startups[[1]]$fundraising$raised_amount
Run Code Online (Sandbox Code Playgroud)

拉出raised_amount列出的第一个元素.但是,我不知道如何将这个应用到4268个初创公司的整个列表中.特别是,我无法弄清楚如何处理分页.我似乎只有一页初创公司(即50个)最多.

我尝试使用for循环来获取启动列表,然后将每个值逐个放入数据帧的一行.下面的例子只显示了一列,但当然我只需通过展开for循环即可为所有这些列做到这一点.但是,我无法在任何其他页面上获得任何内容.

df1 <- as.data.frame(1:length(new$startups))
df1$raiseamnt <- 0

for (i in 1:length(new$startups)) {
  df1$raiseamnt[i] <- new$startups[[i]]$fundraising$raised_amount
}
Run Code Online (Sandbox Code Playgroud)

e:谢谢你提到的分页.我将更仔细地查看文档,看看我是否可以弄清楚如何正确构建API调用以获取不同的页面.如果/当我想出来的时候,我会更新这个答案!

Jae*_*Kim 7

你可能会发现jsonlite包很有用.以下是一个简单的例子.

library(jsonlite)
library(httr)
#request a list of companies currently fundraising using httr
r <- GET("https://api.angel.co/1/startups?filter=raising")
#convert to text object using httr
raise <- content(r, as="text")
#parse JSON
new <- fromJSON(raise)

head(new$startups$id)
[1] 229734 296470 237516 305916 184460 147385
Run Code Online (Sandbox Code Playgroud)

但请注意,此包或问题中的包可以帮助解析JSON字符串,应该适当地创建单个结构,以便可以毫无问题地添加字符串的每个元素,这取决于开发人员.

对于pagnation,API似乎是一个REST API,因此通常会在URL中添加过滤条件(例如https://api.angel.co/1/startups?filter=raising&variable=value).我想它会在API文档的某个地方找到.


tor*_*ina 5

httr库已经导入了jsonlitehttr文档)。具有更好格式输出的更优雅的方法是:

library(httr)    
resp <- httr::GET("https://api.angel.co/1/startups?filter=raising", accept_json())
cont <- content(resp, as = "parsed", type = "application/json")
#explicit convertion to data frame
dataFrame <- data.frame(cont)
Run Code Online (Sandbox Code Playgroud)