【问题标题】:jsonlite::toJSON too many `[]` brackets in R - unbox jsonR中的jsonlite :: toJSON太多`[]`括号 - 拆箱json
【发布时间】:2018-10-19 11:59:25
【问题描述】:

我目前正在构建一个包含多层信息的 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]>

当我使用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"))

【问题讨论】:

    标签: r tibble jsonlite


    【解决方案1】:

    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)
    

    【讨论】:

    • 不错,您找到了解决方案。我刚刚写了一个丑陋的解决方案(将每个数据帧转换为一个列表),但现在不需要发布它。我不知道unbox 函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多