没有外方括号的 toJSON

toJSON without outer square brackets

我正在使用 jsonlite 中的 toJSON() 将特定结构的嵌套列表(API 需要)转换为 JSON。但是,我需要最后的 JSON 不包含外部方括号(API 也需要)。

test_list <- list(
    list(formName = "test_title", user_id = "test_userid", rows = list(list(row = 0))), 
    list(formName = "test_title2", user_id = "test_userid2", rows = list(list(row = 0)))
)

jsonlite::toJSON(test_list, pretty = TRUE, auto_unbox = TRUE)

给出:

[
  {
    "formName": "test_title",
    "user_id": "test_userid",
    "rows": [
      {
        "row": 0
      }
    ]
  },
  {
    "formName": "test_title2",
    "user_id": "test_userid2",
    "rows": [
      {
        "row": 0
      }
    ]
  }
] 

但我需要删除第一个和最后一个方括号。

我可以使用 purrr::flatten() 删除列表的顶层,从而删除 JSON 中的方括号,但是 toJSON() 似乎没有喜欢列表有重复的名称,并将它们重命名为 name.1、name.2、name.3 等(API 也不允许这样做)。

即:

jsonlite::toJSON(test_list %>% purrr::flatten(), pretty = TRUE, auto_unbox = TRUE)

移除外部方括号,但将第二个元素中的名称转换为 formName.1、user_id.1、rows.1,如下所示:

{
  "formName": "test_title",
  "user_id": "test_userid",
  "rows": [
    {
      "row": 0
    }
  ],
  "formName.1": "test_title2",
  "user_id.1": "test_userid2",
  "rows.1": [
    {
      "row": 0
    }
  ]
}

但这就是我需要的:

{
  "formName": "test_title",
  "user_id": "test_userid",
  "rows": [
    {
      "row": 0
    }
  ],
  "formName": "test_title2",
  "user_id": "test_userid2",
  "rows": [
    {
      "row": 0
    }
  ]
}

即formName,user_ud和第二个JSON元素中的行没有附加“.1”

如有任何建议,我们将不胜感激!

只需编辑 JSON。您可以使用 gsubstringr 来完成。如果你使用stringr函数,它会失去它的"json" class,但你可以把它放回去:

> x = jsonlite::toJSON(test_list %>% purrr::flatten(), pretty = TRUE, auto_unbox = TRUE)
> gsub("user_id\.1", "user_id", x)
{
  "formName": "test_title",
  "user_id": "test_userid",
  "rows": [
    {
      "row": 0
    }
  ],
  "formName.1": "test_title2",
  "user_id": "test_userid2",
  "rows.1": [
    {
      "row": 0
    }
  ]
}

> y = stringr::str_replace_all(x, "user_id\.1", "user_id")
> class(y) = "json"
> y
{
  "formName": "test_title",
  "user_id": "test_userid",
  "rows": [
    {
      "row": 0
    }
  ],
  "formName.1": "test_title2",
  "user_id": "test_userid2",
  "rows.1": [
    {
      "row": 0
    }
  ]
} 

我会留给你编写适当的正则表达式来进行你想要的替换。

这似乎可行(丑陋但简单):

df = data.frame(a=1,b=2)
js = toJSON(unbox(fromJSON(toJSON(df))))
> js
{"a":1,"b":2} 

出于某种原因,auto_unbox=T 不起作用:

> toJSON(df,auto_unbox = T)
[{"a":1,"b":2}]