目前,我正在构建一个具有多层信息的api。目前,我正在使用小标题并将信息嵌套在列下:
# A tibble: 1 x 3
APICallTimeGMT Error some_data
<dttm> <list> <list>
1 2018-10-19 11:43:10 <data.frame [1 × 2]> <tibble [2 × 3]>
当我使用JSON
将其转换为jsonlite::toJSON
时,会得到很多[]
括号。有没有一种方法可以将这些特定对象变成json对象而不是列表。那么,嵌套对象应该是什么类(而不是data.frame)?
当前输出:
所需的输出:
以下是dput(x)
的可重复性:
structure(list(APICallTimeGMT = structure(1539949390.26164, class = c("POSIXct",
"POSIXt")), Error = list(structure(list(msg = structure(1L, .Label = "OK", class = "factor"),
status = 200), .Names = c("msg", "status"), row.names = c(NA,
-1L), class = "data.frame")), some_data = list(structure(list(
Outcome = c("Case1", "Case2"), predictions = list(structure(list(
ClassA = 0.4, ClassB = 0.1, ClassC = 0.5), .Names = c("ClassA",
"ClassB", "ClassC"), row.names = c(NA, -1L), class = "data.frame"),
structure(list(ClassA = 0.4, ClassB = 0.1, ClassC = 0.5), .Names = c("ClassA",
"ClassB", "ClassC"), row.names = c(NA, -1L), class = "data.frame")),
meta = list(structure(list(model = structure(1L, .Label = "Awesome AI", class = "factor"),
runs = 55), .Names = c("model", "runs"), row.names = c(NA,
-1L), class = "data.frame"), structure(list(model = structure(1L, .Label = "Awesome AI", class = "factor"),
runs = 55), .Names = c("model", "runs"), row.names = c(NA,
-1L), class = "data.frame"))), row.names = c(NA, -2L), class = c("tbl_df",
"tbl", "data.frame"), .Names = c("Outcome", "predictions", "meta"
)))), row.names = c(NA, -1L), .Names = c("APICallTimeGMT", "Error",
"some_data"), class = c("tbl_df", "tbl", "data.frame"))
答案 0 :(得分:1)
斯特凡·洛朗的答案很接近。似乎问题在于,如果数据位于嵌套小波auto-unbox = TRUE
中,则某种程度上会失败。为了正确地在上面打印数据,我使用了mutate
+ purrr
:
library(jsonlite)
x_unboxed <- x %>%
mutate(Error = map(Error, ~.x %>% unbox),
some_data = map(some_data, ~.x %>%
mutate(predictions = map(predictions, ~.x %>% unbox),
meta = map(meta, ~.x %>% unbox)))) %>%
unbox
x_unboxed %>% toJSON(., pretty = T)