JSON R 中的数组 - {jsonlite}

JSON arrays in R - {jsonlite}

我目前正在编写一个轻量级的 API 包装器,并且对 POST 请求的 JSON 有效载荷有点头疼。
您可以在下面找到调用 api:

所需的 JSON 结构
{
    "points": [
        {
            "coord": [40.1, -73.0],
            "id": "test1"
        },
        {
            "coord": [37.784, -122.402]
        },
        {
            "coord": [41.84, -73],
            "id": "test2"
        }
    ]
}

在我开始使用 jsonlite 的地方,我遇到的困难是将 coord 值作为数组(截至目前,我刚刚设法将它们解析为字符串).我可能遗漏了一些相当简单的东西。

library(jsonlite)

df <- data.frame(id = c(123, 456),
           coord = c("41.889083,12.470514",
                     "41.899009,12.477243"))

jsonified <- toJSON(list(`points` = df), pretty = T)

jsonified

将坐标拆分为长度为 2 的字符串向量列表。确保 coord 不是因子或将其转换为字符(我在创建数据框时添加了 stringsAsFactor = FALSE)。

df$coord <- strsplit(df$coord, ",")
df
#>    id                coord
#> 1 123 41.889083, 12.470514
#> 2 456 41.899009, 12.477243

jsonlite::toJSON(list(`points` = df), pretty = TRUE)
#> {
#>   "points": [
#>     {
#>       "id": 123,
#>       "coord": ["41.889083", "12.470514"]
#>     },
#>     {
#>       "id": 456,
#>       "coord": ["41.899009", "12.477243"]
#>     }
#>   ]
#> }