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

如何使用Jolt Spec实现JSON对象合并、嵌套数组移除及指定对象清理

Jolt数据合并与数组扁平化实现方案

输入JSON

{
  "info": [
    {"item": "sugar","price": 4,"state": "Alberta","country": "Canada"},
    {"item": "sugar","price": 4.5,"state": "California","country": "US"}
  ],
  "location": {
    "continent": [
      {"country": "US","coordinates": {"lang": "97º 00' W","long": "38º 00' N"}},
      {"country": "Canada","coordinates": {"lang": "95° 00' W","long": "60° 00' N"}}
    ]
  },
  "metarecord": {"continent": "North America"}
}

需求

  • 移除所有嵌套数组,将数据整合成一维对象数组
  • 依据country字段匹配,把location.continent中对应国家的lang、long字段合并到info的对应对象中
  • 给info的每个对象添加metarecord.continent字段值
  • 最终剔除location和metarecord这两个顶层对象

尝试的Jolt Spec(未达到预期)

[
  {
    "operation": "shift",
    "spec": {
      "info": {
        "*": {
          "item": "[&1].item",
          "price": "[&1].price",
          "state": "[&1].state",
          "country": "[&1].country"
        }
      },
      "location": {
        "continent": {
          "@": "[&1].continent"
        }
      },
      "metarecord": {
        "continent": {
          "*": {
            "$": "[&2].&1"
          }
        }
      }
    }
  }
]

错误输出

[
  {"item": "sugar","price": 4,"state": "Alberta","country": "Canada"},
  {"item": "sugar","price": 4.5,"state": "California","country": "US"}
]

正确的Jolt Spec

[
  {
    "operation": "shift",
    "spec": {
      "info": {
        "*": {
          // 保留info对象原有所有字段
          "@": "[&1].&",
          // 引入metarecord的continent字段到当前对象
          "@(2,metarecord.continent)": "[&1].continent",
          // 通过country字段匹配location中对应国家的坐标数据
          "@(2,location.continent[#2].coordinates.lang)": "[&1].lang",
          "@(2,location.continent[#2].coordinates.long)": "[&1].long"
        }
      }
    }
  }
]

说明

  • @ 用于直接保留当前层级的所有字段,避免逐个字段手动映射
  • @(2,metarecord.continent) 表示向上遍历2层获取metarecord.continent的值,赋值给当前对象的continent字段
  • @(2,location.continent[#2].coordinates.lang) 中#2引用当前info对象的country字段值,以此匹配location.continent数组中对应国家的坐标数据,实现按国家关联合并

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 14:53:14