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

JOLT嵌套数组转换问题求助:求正确转换Spec实现目标JSON

JOLT转换解决方案

场景1:将characteristic数组转为对象键值对

输入JSON

{"id": "Root_ID","Item": [{"id": "ID_1","characteristic": [{"name": "char1","value": "PRE1"},{"name": "char2","value": "2050-01-01"}]},{"id": "ID_2","characteristic": [{"name": "char1","value": "PRE2"},{"name": "char2","value": "2050-01-02"}]}]}

期望输出

{"id": "Root_ID","Item": [{"id": "ID_1","char1": "PRE1","char2": "2050-01-01"},{"id": "ID_2","char1": "PRE2","char2": "2050-01-02"}]}

原Spec问题分析

原Spec存在两处问题:

  1. 输出数组键名误写为小写item,与期望的大写Item不匹配
  2. 冗余枚举char1/char2,未利用JOLT的动态匹配能力,导致逻辑复杂且扩展性差

正确JOLT转换Spec

[
  {
    "operation": "shift",
    "spec": {
      "id": "id",
      "Item": {
        "*": {
          "id": "Item[#1].id",
          "characteristic": {
            "*": {
              "value": "Item[#3].@(1,name)"
            }
          }
        }
      }
    }
  }
]

逻辑说明

  • 直接保留根节点的id字段
  • 遍历Item数组的每个元素(*代表数组索引):
    • 将当前Item的id字段映射到对应索引的目标位置
    • 遍历每个characteristic数组元素,用@(1,name)获取当前元素的name值作为目标键,value作为对应值;通过#3定位到外层Item数组的索引(层级关系:characteristic数组层→Item元素层→Item数组层,共3层)

场景2:选择性保留指定字段

期望输出

{"id": "Root_ID","Item": [{"id": "ID_1","char1": "PRE1"},{"id": "ID_2","char1": "PRE2","char2": "2050-01-02"}]}

调整后的JOLT转换Spec

[
  {
    "operation": "shift",
    "spec": {
      "id": "id",
      "Item": {
        "0": { // 匹配第一个Item(索引0,对应ID_1)
          "id": "Item[0].id",
          "characteristic": {
            "*": {
              "name": {
                "char1": { "@(2,value)": "Item[0].char1" }
              }
            }
          }
        },
        "1": { // 匹配第二个Item(索引1,对应ID_2)
          "id": "Item[1].id",
          "characteristic": {
            "*": {
              "value": "Item[1].@(1,name)"
            }
          }
        }
      }
    }
  }
]

逻辑说明

  • 通过指定数组索引(0和1)分别处理两个Item元素:
    • 对索引0的Item(ID_1),仅匹配char1字段进行转换
    • 对索引1的Item(ID_2),保留所有characteristic的键值对
  • 若Item的id是固定标识而非依赖索引,也可通过@(1,id)精准匹配,比如把"0"替换为"*": { "id": { "ID_1": { ... } } }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 08:05:23