Python 从R中API响应中的数据帧列表返回列子集
我是一个API新手,自学如何在R中与Planet Labs的API交互,但Planet的文档是针对Python的,我不熟悉Python(因此在R中工作) 在其中一个示例中,它们提供了一些python/curl/jq代码,用于从列表中的数据帧返回列Python 从R中API响应中的数据帧列表返回列子集,python,r,api,curl,httr,Python,R,Api,Curl,Httr,我是一个API新手,自学如何在R中与Planet Labs的API交互,但Planet的文档是针对Python的,我不熟悉Python(因此在R中工作) 在其中一个示例中,它们提供了一些python/curl/jq代码,用于从列表中的数据帧返回列 ➜ curl -L -H "Authorization: api-key $PL_API_KEY" \ 'https://api.planet.com/data/v1/item-types' | jq '.item_typ
➜ curl -L -H "Authorization: api-key $PL_API_KEY" \
'https://api.planet.com/data/v1/item-types' | jq '.item_types[].id'
"REOrthoTile" # This is the desired output
"PSOrthoTile" # Desired output
我的问题是:如何将上面代码的jq部分合并到R中的API请求中,以便响应只包含相关列,而不是整个列表和数据帧?我可以通过从较大的列表和数据帧中进行子集设置来实现这一目标,但我正试图避免用所有不需要的信息混淆API响应
library(httr)
library(jsonlite)
key = "my_Planet_API_key"
res = GET("https://api.planet.com/data/v1/item-types",
authenticate(user = key, password = ""))
>res
Response [https://api.planet.com/data/v1/item-types]
Date: 2020-09-11 17:29
Status: 200
Content-Type: application/json
Size: 7.43 kB
{"_links":{"_self":"https://api.planet.com/data/v1/item-type...
data = fromJSON(rawToChar(res$content))
>summary(data)
Length Class Mode
_links 1 -none- list
item_types 5 data.frame list
> str(data, vec.len = 1)
List of 2
$ _links :List of 1
..$ _self: chr "https://api.planet.com/data/v1/item-types/"
$ item_types:'data.frame': 15 obs. of 5 variables:
..$ _links :'data.frame': 15 obs. of 1 variable:
.. ..$ _self: chr [1:15] "https://api.planet.com/data/v1/item-types/PSOrthoTile" ...
..$ display_description : chr [1:15] "PlanetScope orthorectified 4-band imagery as 25km x 25km UTM tiles" ...
..$ display_name : chr [1:15] "PlanetScope Ortho Tile" ...
..$ id : chr [1:15] "PSOrthoTile" ...
..$ supported_asset_types:List of 15
.. ..$ : chr [1:11] "analytic" ...
.. ..$ : chr [1:6] "analytic" ...
.. ..$ : chr [1:16] "analytic" ...
.. ..$ : chr [1:23] "analytic" ...
.. ..$ : chr [1:16] "basic_analytic_b1" ...
.. ..$ : chr [1:14] "analytic_b1" ...
.. ..$ : chr [1:15] "analytic_b1" ...
.. ..$ : chr [1:26] "analytic" ...
.. ..$ : chr [1:12] "ortho_analytic" ...
.. ..$ : chr [1:3] "video_file" ...
.. ..$ : chr [1:4] "ortho_analytic_hh" ...
.. ..$ : chr [1:22] "analytic_gflags" ...
.. ..$ : chr [1:8] "analytic_granule_pnt" ...
.. ..$ : chr [1:22] "analytic_gflags" ...
.. ..$ : chr [1:8] "analytic_granule_pnt" ...
names(data$item_types)
[1] "_links" "display_description"
[3] "display_name" "id"
[5] "supported_asset_types"
data$item_types$id # Desired output should be same as Python output above
谢谢 本质上,
jq
是一个单独安装的命令行模块,可以在curl
检索或任何不限于curl
的JSON后提取或转换JSON数据。因此,它不会比R的httr
调用做更多的工作。看
为了避免未指定的API信息,只需通过名称链接从返回对象中提取所需项:
data = fromJSON(rawToChar(res$content))$item_types$id
data = fromJSON(rawToChar(res[["content"]]))[["item_types"]][["id"]]
在给出代码答案时,请始终添加解释。
as.data.frame(list.flatten(res[['']])) %>% select()