【问题标题】:Converting R data frame to JSON while separating each row into a new JSON object将 R 数据帧转换为 JSON,同时将每一行分成一个新的 JSON 对象
【发布时间】:2023-03-18 07:12:01
【问题描述】:

我有一个 R 数据框,我想将其转换为 JSON,但我想将每一行插入到名为“traits”的新 JSON 对象中。我尝试将特征列作为第一列并将新数据框转换为 JSON,但这不会产生正确的输出。我还尝试将“特征”:{ 对象附加到每个转换的 JSON 输出,但这也失败了。我正在尝试在数据框内工作,然后将其转换为 JSON,因为 toJSON 会在括号 [] 中生成一个列表,我也无法绕过它。我正在使用 jsonlite

color = c('red','blue','green')
fruit = c('apple','orange','grape')
animal = c('cat','dog','chicken')
df<- data.frame(color, fruit, animal)
toJSON(df, pretty= TRUE)

我希望它看起来像这样:

[
  { "traits": {
      "color": "red",
      "fruit": "apple",
      "animal": "cat"
  }
    },

【问题讨论】:

    标签: r json dataframe


    【解决方案1】:

    这是一种方法:

    L <- list(list(traits = as.list(df[1,])), 
              list(traits = as.list(df[2,])),
              list(traits = as.list(df[3,])))
    

    > toJSON(L, pretty = TRUE, auto_unbox = TRUE)
    [
      {
        "traits": {
          "color": "red",
          "fruit": "apple",
          "animal": "cat"
        }
      },
      {
        "traits": {
          "color": "blue",
          "fruit": "orange",
          "animal": "dog"
        }
      },
      {
        "traits": {
          "color": "green",
          "fruit": "grape",
          "animal": "chicken"
        }
      }
    ] 
    

    要获取此列表L,您可以这样做

    L <- apply(df, 1, function(x) list(traits = as.list(x)))
    

    另一种方式是:

    df2 <- purrr::transpose(lapply(df, function(x) as.character(x)))
    L <- lapply(df2, function(x) list(traits = x))
    

    df <- data.frame(color, fruit, animal, stringsAsFactors = FALSE)
    L <- lapply(purrr::transpose(df), function(x) list(traits = x))
    

    【讨论】:

    • 这很有帮助,谢谢。它完全按照需要实现了特征,但我注意到它将 JSON 对象的每个值都放在括号中,所以它看起来像这样:"animal" : ["chicken"] 而不是 "animal" : "chicken"
    • @Milan 这就是我使用auto_unbox = TRUE的原因。
    • @Milan Nice。请考虑accepting the answer。否则,您的问题将被 SO 视为未回答。
    猜你喜欢
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 2019-07-29
    相关资源
    最近更新 更多