r语言 - 从API响应列表中提取数据



我从API调用中提取的数据看起来像这样。请记住,dput中99%的数据是无用的,我只是需要它来重现这个问题。运行它应该返回如下的响应:

[[1]]
Response [https://test.api.com/v4/12345/information]
Date: 2021-09-02 20:24
Status: 204
Content-Type: <unknown>
<EMPTY BODY>
[[2]]
Response [https://test.api.com/v4/23456/information]
Date: 2021-09-02 20:24
Status: 204
Content-Type: <unknown>
<EMPTY BODY>

我想做的是从这些响应中提取信息,看起来像这样:

<表类>url日期状态tbody><<tr>https://test.api.com/v4/12345/information9/2/21 20:24204https://test.api.com/v4/23456/information9/2/21 20:24204

正如您提到的,您可以为一个burb运行response_blurb$url,但对于blurbs列表,您必须执行response_blurb[[1]]$url

可以展开以捕获您想要的三个变量response_blurb[[1]][c('url', 'date', 'status_code')]。这可以通过sapply[[1]][[2]]上迭代。

all together

sapply(response_blurb, '[', c('url', 'date', 'status_code'))

或返回一个数据帧

data.frame(t(sapply(response_blurb, '[', c('url', 'date', 'status_code'))))
#-----
url       date status_code
1 https://test.api.com/v4/12345/information 1630614283         204
2 https://test.api.com/v4/23456/information 1630614283         204

你可以试试:

library(purrr)
library(magrittr)
response_blurb %>% 
map_df(~.x %>% 
extract(c("url", "date", "status_code")))

返回

# A tibble: 2 x 3
url                                       date                status_code
<chr>                                     <dttm>                    <int>
1 https://test.api.com/v4/12345/information 2021-09-02 20:24:43         204
2 https://test.api.com/v4/23456/information 2021-09-02 20:24:43         204

编辑感谢nniloc的评论,这可以缩短为

response_blurb %>% 
map_df(extract, c("url", "date", "status_code"))

最新更新