You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将R语言DataFrame转换为指定嵌套格式的JSON文件?

实现指定嵌套结构的JSON输出

首先,先还原你提供的DataFrame:

library(dplyr)
library(jsonlite)
library(tidyr)
library(purrr)

# 构造示例数据
df <- tibble(
  date = c("2018-12-02", "2018-12-05", "2018-12-05", "2018-12-08"),
  aid = c(10, 4, 6, 6),
  x_axis = c(1.072, -1.9322222, 0.038, 1.3677143),
  y_axis = c(9.462, 5.654278, 8.662714, 9.199286),
  z_axis = c(0.083, 6.7933333, 3.9418571, 0.258)
)

接下来按需求处理数据并生成JSON:

步骤1:分组计算均值

按date和aid分组,计算每个组下三个轴的均值:

mean_df <- df %>%
  group_by(date, aid) %>%
  summarise(
    x_axis = mean(x_axis),
    y_axis = mean(y_axis),
    z_axis = mean(z_axis),
    .groups = "drop"
  )

步骤2:整理成目标嵌套结构

将数据转换为date为顶层分组,每个date下嵌套对应aid及mean层级的结构:

nested_list <- mean_df %>%
  group_by(date) %>%
  group_split() %>%
  lapply(function(group) {
    # 提取当前分组的date值
    date_val <- unique(group$date)
    # 构造每个aid对应的mean嵌套部分
    aid_items <- group %>%
      select(aid, x_axis, y_axis, z_axis) %>%
      nest(data = -aid) %>%
      mutate(data = map(data, ~ list(mean = as.list(.x)))) %>%
      deframe()
    # 组合date字段和所有aid条目
    c(list(date = date_val), aid_items)
  })

步骤3:转换为JSON

使用jsonlite::toJSON()生成格式化的目标JSON:

output_json <- toJSON(nested_list, pretty = TRUE, auto_unbox = TRUE)
cat(output_json)

最终输出结果

执行后会得到如下格式的JSON:

[
  {
    "date": "2018-12-02",
    "10": {
      "mean": {
        "x_axis": 1.072,
        "y_axis": 9.462,
        "z_axis": 0.083
      }
    }
  },
  {
    "date": "2018-12-05",
    "4": {
      "mean": {
        "x_axis": -1.9322222,
        "y_axis": 5.654278,
        "z_axis": 6.7933333
      }
    },
    "6": {
      "mean": {
        "x_axis": 0.038,
        "y_axis": 8.662714,
        "z_axis": 3.9418571
      }
    }
  },
  {
    "date": "2018-12-08",
    "6": {
      "mean": {
        "x_axis": 1.3677143,
        "y_axis": 9.199286,
        "z_axis": 0.258
      }
    }
  }
]

关键说明

  • nest和map配合实现了mean层级的嵌套构造,deframe将aid值转为列表的键,符合目标格式要求。
  • auto_unbox=TRUE确保单个数值不会被包裹为数组,与示例格式一致。

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 23:20:18