r - 将 JSON 传递到 R 函数

标签 r json string

我正在尝试将以下 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/

相关文章:

c - C-within-R 代码中的特征值计算

r - 将在 for 循环中创建的多个 ggplots 保存到单个图

php - MySQL/PHP : How to get columns and associated data

java - 用java解析JSON : dynamic keys

javascript - 如何在 Shiny 的仪表板侧栏中手动展开子菜单

R : read timeseries data using xts package

javascript - 如何在 JavaScript 中自动完成 API 调用的 JSON 响应?

javascript - 搜索数组时出现问题

java - RegExpr 输出不正确

C 字符串格式化