I have a api call that yields a list of lists as the response. I would really like to see the response in the form of a dataframe, but cannot get that working by myself.
I wonder if anyone can help?
objectIds <- c(746, 3733, 2271, 2337, 3385, 3610, 2921, 1741, 1883, 885)
snes_url <- "https://services1.arcgis.com/gtRkYQyUQLMTM1uS/ArcGIS/rest/services/Species_of_National_Environmental_Significance_Distributions_(public_grids)/FeatureServer/0/query"
# here is the query, the actual number of objectIds I might require is arbitrary (though <2000)
full_query_params <- list(
where = glue::glue("OBJECTID IN ({toString(objectIds[1:5])})"),
outFields = "*",
outSR = 4326,
f = "json"
)
# set the request
dat_req <-request(snes_url)
# Add the query parameters using req_url_query
dat_req <- dat_req |> req_url_query(!!!full_query_params)
# Perform the request and get the response
my_response <- dat_req |>
req_perform() |>
resp_body_json()
bb <- my_response |> pluck('features')
bb[[1]]$attributes # these are the data I want in a dataframe, one row per objectID (or in this example, one row per bb list item, bb[[1]], bb[[22]], bb[[3]]), one column per field.
# this is one of the methods I have tried for creating a dataframe, but not got to work.
extracted_data <- my_response |>
pluck('features') |>
map_dfr( # iterates over each list and binds rows to a tibble
\(x) {
tibble(
OBJECTID = x |> pluck('OBJECTID'),
SCIENTIFIC_NAME = x |> pluck('SCIENTIFIC_NAME '),
VERNACULAR_NAME = x |> pluck('VERNACULAR_NAME'),
TAXON_GROUP = x |> pluck('TAXON_GROUP')
)
}
)
extracted_data
I was more or less following this guide: https://albert-rapp.de/posts/web_dev/07_httr2_ultimate_guide/07_httr2
Don't parse geojson/json to list. Rather use it as an object. Below an example with {jsonlite}
Created on 2024-03-18 with reprex v2.1.0