"Error in parse_url(url) : length(url) == 1 is not TRUE" in GET() function

I'm trying to convert three lines of R code into an elegant one liner using %>% for a bit of fairly simple code that gets data from an API, transforms the Unicode into JSON and then into a char type that I can use as data.

Libraries: httr, jsonlite, tidyverse

This works:
</> res = GET("http://api.open-notify.org/astros.json")
</>rawToChar(res$content)
</>data = fromJSON(rawToChar(res$content))

Because I like slick, I wanted to make those three lines into one command using %>%, like so:
</>data <- fromJSON(rawToChar(res$content)) %>% GET("http://api.open-notify.org/astros.json")

But that fails with this error code:

Error in parse_url(url) : length(url) == 1 is not TRUE

Any idea why?

Many thanks in advance!

  • Annett

Your one-line version is more or less backwards. You are sending the result of fromJSON() into GET(). I think you want

data <- GET("http://api.open-notify.org/astros.json") %>% 
        `$`("content") %>% rawToChar() %>% fromJSON()

Using $ as a function is unusual but it can be done.

DF <-  data.frame(Val = 1:4, Val2 = 2:5)
`$`(DF, "Val2")
#> [1] 2 3 4 5

Created on 2020-11-16 by the reprex package (v0.3.0)

1 Like

Thank you so much - that worked like a charm! I had tried it the other way around at first but that didn't work either. I have not used '$' before, that is very neat. Thanks so much!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.