Search code examples
rhttr

Write all items from list to a character vector from GET httr request


I am trying to extract data from a GET request and parse it as below:

# Function to get details from all experiments
getData<- function()
{
  server_url <- "http://127.0.0.1:5000/experiments"
  r <- GET(url = server_url, verbose())
  return(r)
}

# Get all experiments
x <- getData()

# Retrieve content and parse for processing
y <- content(x, "parsed")

The output is as follows i.e. a single list containing all 17 experiments.

> y
$experiments
$experiments[[1]]
$experiments[[1]]$end
NULL

$experiments[[1]]$id
[1] 1

$experiments[[1]]$name
[1] "reprehenderit"

$experiments[[1]]$start
[1] "Mon, 30 Mar 2015 17:29:13 GMT"


$experiments[[2]]
$experiments[[2]]$end
NULL

$experiments[[2]]$id
[1] 2

$experiments[[2]]$name
[1] "explicabo"

$experiments[[2]]$start
[1] "Mon, 30 Mar 2015 17:29:44 GMT"

.......

$experiments[[17]]
$experiments[[17]]$end
NULL

$experiments[[17]]$id
[1] 17

$experiments[[17]]$name
[1] "dsagfsdzg"

$experiments[[17]]$start
[1] "Wed, 01 Apr 2015 01:45:01 GMT"

I want to extract 17 "name" elements from this list of elements into a single character vector (have done it manually for the first 2 elements).

z <- c(unlist(y[[1]][1])["name"], unlist(y[[1]][2])["name"])
z

           name            name 
"reprehenderit"     "explicabo" 

Could anyone help me automate the above? Is there a simple way to extract this from the GET request?


Solution

  • You can use sapply over the y[[1]], which is a vector of lists, according to your code above:

    > names <- sapply(y[[1]], function(x) x["name"])
    > names
    [1] "reprehenderit" "explicabo" ... "dsagfsdzg"