Passing JSON into R function

Viewed 52

I am trying to pass the following JSON into a function in R.

The raw JSON

{
    "type": "Polygon",
    "coordinates": [
    [
       [-122.68,42.77],
       [-116.53,42.77],
       [-116.53,44.30],
       [-122.68,44.30],
       [-122.68,42.77]
    ]
  ]
}

And here's the call to an R function:

myfunction(api_endpoint="my_api_endpoint", args=list(arg1 = 2000, arg2=MY_JSON_HERE)

I have tried escaping quotes, wrapping in single quotes and I keep getting errors about curly braces etc.

How do I take that literal JSON string and send it into an R function please?

2 Answers

With R>4.0 the new raw string syntax r"(...)" avoids the quotes / double quotes hassle:

json <- r"(
{
    "type": "Polygon",
    "coordinates": [
    [
       [-122.68,42.77],
       [-116.53,42.77],
       [-116.53,44.30],
       [-122.68,44.30],
       [-122.68,42.77]
    ]
  ]
}
)"
f <- function(json) {jsonlite::fromJSON(json)}

f(json)

$type
[1] "Polygon"

$coordinates
, , 1

        [,1]    [,2]    [,3]    [,4]    [,5]
[1,] -122.68 -116.53 -116.53 -122.68 -122.68

, , 2

      [,1]  [,2] [,3] [,4]  [,5]
[1,] 42.77 42.77 44.3 44.3 42.77

Otherwise, in this case, you could also pass json as string with simple quotes :

json <- '{
    "type": "Polygon",
    "coordinates": [
    [
       [-122.68,42.77],
       [-116.53,42.77],
       [-116.53,44.30],
       [-122.68,44.30],
       [-122.68,42.77]
    ]
  ]
}
'

The simple trick that helped me was to transform the json string, that is input into the function, via fromJSON:

myfunction <- function(json){
jsonlite::fromJSON(json)
}

That way the string is no longer interpreted as a character string, which messes things up with backslashes etc., but as an atomic list object with json structure.

Related