我正在使用 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)
Run Code Online (Sandbox Code Playgroud)
这使:
[
{
"formName": "test_title",
"user_id": "test_userid",
"rows": [
{
"row": 0
}
]
},
{
"formName": "test_title2",
"user_id": "test_userid2",
"rows": [
{
"row": 0
}
]
}
]
Run Code Online (Sandbox Code Playgroud)
但我需要删除第一个和最后一个方括号。
我可以使用 purrr::flatten() 删除列表的顶层,从而删除 JSON 中的方括号,但 toJSON() 似乎不喜欢列表有重复的名称,并将它们重命名为 name. 1、name.2、name.3 等(API 也不允许)。
那是:
jsonlite::toJSON(test_list %>% purrr::flatten(), pretty = TRUE, auto_unbox = TRUE)
Run Code Online (Sandbox Code Playgroud)
它删除了外部方括号,但将第二个元素中的名称转换为 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
}
]
}
Run Code Online (Sandbox Code Playgroud)
但这就是我需要的:
{
"formName": "test_title",
"user_id": "test_userid",
"rows": [
{
"row": 0
}
],
"formName": "test_title2",
"user_id": "test_userid2",
"rows": [
{
"row": 0
}
]
}
Run Code Online (Sandbox Code Playgroud)
即,第二个 JSON 元素中的 formName、user_ud 和行不附加“.1”
任何建议将不胜感激!
小智 5
这似乎有效(丑陋但简单):
df = data.frame(a=1,b=2)
js = toJSON(unbox(fromJSON(toJSON(df))))
> js
{"a":1,"b":2}
Run Code Online (Sandbox Code Playgroud)
由于某种原因, auto_unbox=T 不起作用:
> toJSON(df,auto_unbox = T)
[{"a":1,"b":2}]
Run Code Online (Sandbox Code Playgroud)
只需编辑 JSON 即可。您可以使用gsub或 来完成stringr。如果你使用stringr函数,它将失去它的"json"类,但你可以把它放回去:
> 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
}
]
}
Run Code Online (Sandbox Code Playgroud)
我将让您编写适当的正则表达式来进行您想要的替换。