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

如何在Jolt转换中遍历子数组并提取键值对?

解决Jolt多层嵌套数组遍历提取问题

输入JSON示例

{
  "data": [
    {
      "id": 1,
      "name": "Level1",
      "children": [
        {
          "id": 11,
          "name": "Level2",
          "children": [
            {
              "id": 111,
              "name": "Level3"
            }
          ]
        }
      ]
    },
    {
      "id": 2,
      "name": "Level1-2"
    }
  ]
}

原尝试的Jolt Shift配置

[
  {
    "operation": "shift",
    "spec": {
      "data": {
        "*": {
          "id": "[&1].id",
          "name": "[&1].name"
        }
      }
    }
  }
]

当前输出(仅提取第一层)

[
  {
    "id": 1,
    "name": "Level1"
  },
  {
    "id": 2,
    "name": "Level1-2"
  }
]

期望输出(遍历所有嵌套数组)

[
  {
    "id": 1,
    "name": "Level1"
  },
  {
    "id": 11,
    "name": "Level2"
  },
  {
    "id": 111,
    "name": "Level3"
  },
  {
    "id": 2,
    "name": "Level1-2"
  }
]

修正后的Jolt配置(两种方案)

方案一:递归Shift遍历嵌套数组

[
  {
    "operation": "shift",
    "spec": {
      "data": {
        "*": {
          // 提取当前层级的id和name到临时数组
          "id": "ids[]",
          "name": "names[]",
          // 递归处理children,将子元素的内容回传到上层data的数组节点
          "children": {
            "*": {
              "@": "&3"
            }
          }
        }
      }
    }
  },
  // 将ids和names数组对应位置的元素组合成对象
  {
    "operation": "shift",
    "spec": {
      "ids": {
        "*": "[&1].id"
      },
      "names": {
        "*": "[&1].name"
      }
    }
  }
]

方案二:先扁平化再提取(更简洁)

[
  {
    "operation": "recursiveSquash",
    "spec": {
      "children": "" // 将所有children下的元素拉平到父层级
    }
  },
  {
    "operation": "shift",
    "spec": {
      "data": {
        "*": {
          "id": "[&1].id",
          "name": "[&1].name"
        }
      }
    }
  }
]

说明

  • 方案一通过递归传递子元素的路径,实现多层数组的遍历提取,最后将分散的键值对重新组合成对象。
  • 方案二利用recursiveSquash操作直接扁平化所有嵌套的children节点,把所有层级的元素放到同一层级,之后用普通的Shift操作即可提取全部数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 13:05:23