如果我运行本文底部的代码,我会得到下面的 json 文本。我如何摆脱所有
[
和 ]
?
输出:
{
"a": [
{
"second": 1
},
{
"second": 2
}
],
"b": [
{
"second": 1
},
{
"second": 2
}
]
}
代码:
tibble::tibble(
first = c("a","a","b","b"),
second = c(1,2,1,2)
)|>
tidyr::nest(.by = first)|>
tidyr::pivot_wider(
names_from = first,
values_from = data
)|>
jsonlite::unbox()|>
jsonlite::toJSON(pretty = T,auto_unbox = T)
您可以在命令末尾添加一行带有
gsub
的内容,即
tibble::tibble(
first = c("a", "a", "b", "b"),
second = c(1, 2, 1, 2)
) |>
tidyr::nest(.by = first) |>
tidyr::pivot_wider(
names_from = first,
values_from = data
) |>
jsonlite::unbox() |>
jsonlite::toJSON(pretty = T, auto_unbox = T) |>
gsub(pattern = "\\[|\\]", replacement = "")
你将获得
{
"a":
{
"second": 1
},
{
"second": 2
}
,
"b":
{
"second": 1
},
{
"second": 2
}
}