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

如何通过JOLT Transformation将嵌套JSON的键移至上层

JOLT转换解决方案

先明确对应需求的典型输入与预期输出(若和你的实际数据结构有出入,可按需调整):

输入JSON示例

{
  "data": {
    "DistrictCount": "2",
    "District1": "朝阳区",
    "District2": "海淀区",
    "extra": "无需保留的字段"
  }
}

预期输出JSON示例

{
  "@context": "http://example.org/contexts/District",
  "type": "DistrictCollection",
  "DistrictCount": 2,
  "districts": [
    {
      "name": "朝阳区"
    },
    {
      "name": "海淀区"
    }
  ]
}

最终JOLT转换Spec

[
  {
    "operation": "shift",
    "spec": {
      "data": {
        "DistrictCount": "DistrictCount",
        "District1": "districts[0].name",
        "District2": "districts[1].name"
      },
      "#http://example.org/contexts/District": "@context",
      "#DistrictCollection": "type"
    }
  },
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "DistrictCount": "=toInteger"
    }
  }
]

各操作说明

  1. Shift操作

    • 把data嵌套对象下的DistrictCount直接映射到顶层同名字段
    • 将District1、District2分别映射到districts数组对应位置的name字段
    • 通过#符号硬编码添加默认的@context和type字段值
  2. Modify操作

    • 用=toInteger函数将DistrictCount的字符串值转换为整数类型

如果你的District字段数量不固定(比如存在District3、District4...),可以用通配符优化Shift规则:

{
  "operation": "shift",
  "spec": {
    "data": {
      "DistrictCount": "DistrictCount",
      "District*": {
        "@": "districts[&1].name"
      }
    },
    "#http://example.org/contexts/District": "@context",
    "#DistrictCollection": "type"
  }
}

这里&1会匹配District*中的数字部分,自动对应数组索引。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 00:45:34