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

如何使用JQ扁平化嵌套JSON数组并重组账户结构

用JQ实现嵌套JSON结构的展开转换

需求描述

需要将包含分组和嵌套用户列表的JSON结构,展开为每个用户条目都携带对应分组信息的扁平化结构,最终输出需保留accounts键,其下每个元素包含group、name、id字段。

原始JSON结构

{
  "accounts": [
    {
      "group": 1,
      "users": [
        {
          "name": "John",
          "id": 1
        },
        {
          "name": "Jane",
          "id": 2
        }
      ]
    },
    {
      "group": 2,
      "users": [
        {
          "name": "Bob",
          "id": 3
        },
        {
          "name": "Mary",
          "id": 3
        }
      ]
    }
  ]
}

目标JSON结构

{
  "accounts": [
    {
      "group": 1,
      "name": "John",
      "id": 1
    },
    {
      "group": 1,
      "name": "Jane",
      "id": 2
    },
    {
      "group": 2,
      "name": "Bob",
      "id": 3
    },
    {
      "group": 2,
      "name": "Mary",
      "id": 3
    }
  ]
}

遇到的问题

尝试使用命令 jq --raw-output '.accounts[].group, .accounts[].users[].name, .accounts[].users[].id' 仅得到零散的字段值,无法生成所需的结构化JSON。


解决方案

使用以下JQ命令即可完成转换:

jq '{ accounts: [ .accounts[] | .group as $g | .users[] | { group: $g, name, id } ] }'

命令解释

  • { accounts: [...] }:构建最终的输出对象,保留accounts键
  • .accounts[]:遍历原始accounts数组中的每个分组对象
  • .group as $g:将当前分组的group值存入变量$g,方便后续引用
  • .users[]:遍历当前分组下的每个用户对象
  • { group: $g, name, id }:将分组ID与用户的name、id字段组合成新的对象

执行该命令后,就能直接得到符合要求的扁平化JSON结构。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:13:17