我目前正在构建一个api,它有几层信息。目前,我正在使用tibble并将信息嵌套在列下:
# 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]>然后,当我使用jsonlite::toJSON将其转换为JSON时,我得到了许多列表[]括号。有没有办法将这些特定的对象转换为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"))发布于 2018-10-19 23:54:38
Stéphane Laurent的回答很接近。看起来问题在于,如果数据在嵌套的碎石中,那么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)https://stackoverflow.com/questions/52891917
复制相似问题