我正在尝试将以下 JSON 传递到 R 中的函数中。
原始 JSON
{
"type": "Polygon",
"coordinates": [
[
[-122.68,42.77],
[-116.53,42.77],
[-116.53,44.30],
[-122.68,44.30],
[-122.68,42.77]
]
]
}
这是对 R 函数的调用:
myfunction(api_endpoint="my_api_endpoint", args=list(arg1 = 2000, arg2=MY_JSON_HERE)
我尝试过转义引号、用单引号括起来,但我不断收到有关大括号等的错误。
如何获取该 JSON 字符串并将其发送到 R 函数中?
最佳答案
使用R>4.0
新的raw string syntax r"(...)"
避免了引号/双引号的麻烦:
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
否则,在这种情况下,您也可以将 json
作为带有简单引号的字符串传递:
json <- '{
"type": "Polygon",
"coordinates": [
[
[-122.68,42.77],
[-116.53,42.77],
[-116.53,44.30],
[-122.68,44.30],
[-122.68,42.77]
]
]
}
'
关于r - 将 JSON 传递到 R 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70883767/