You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何将R数据框转换为每行嵌套在traits对象的JSON格式

解决R数据框转嵌套JSON(每行嵌套在traits对象)的问题

嘿,我懂你要的效果了——把数据框里的每一行都包裹在traits对象里,最终形成一个JSON数组对吧?用jsonlite完全可以实现,你之前的尝试没成功是因为没先把每行数据封装成嵌套结构,我给你调整下代码:

# 先创建你的原始数据框
color = c('red','blue','green')
fruit = c('apple','orange','grape')
animal = c('cat','dog','chicken')
df <- data.frame(color, fruit, animal)

# 关键步骤:将每行数据嵌套进traits对象
library(jsonlite)
nested_data <- lapply(seq(nrow(df)), function(row_idx) {
  list(traits = as.list(df[row_idx, ]))
})

# 转换为指定格式的JSON
toJSON(nested_data, pretty = TRUE)

这段代码的核心逻辑是:用lapply遍历数据框的每一行,把单行数据转成列表后,再嵌套到一个名为traits的列表中,这样生成的嵌套列表再转JSON,就刚好是你想要的结构了。

运行后你会得到如下格式的输出:

[
  {
    "traits": {
      "color": "red",
      "fruit": "apple",
      "animal": "cat"
    }
  },
  {
    "traits": {
      "color": "blue",
      "fruit": "orange",
      "animal": "dog"
    }
  },
  {
    "traits": {
      "color": "green",
      "fruit": "grape",
      "animal": "chicken"
    }
  }
]

内容的提问来源于stack exchange,提问作者Milan

火山引擎 最新活动