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

JOLT技术实现:仅转换非空列表,保留输入空列表字段

JOLT转换JSON数组时保留指定空列表的实现方案

需求描述

需要将JSON数组中list字段的每个条目转换为包含listType(固定值"1")和listValue(原条目值)的对象;同时需满足:

  • 若输入中list为空数组[],转换后需保留该空数组
  • 若输入中不存在list字段,转换后也不新增该字段
  • 可选接受将输入的list: null转换为list: []

现有问题

当前使用的JOLT规范仅能处理非空list的转换,当输入list为空数组时,该字段会被忽略,无法保留;而使用default操作会在无list字段时自动添加空数组,不符合需求。

输入输出示例

基础示例

输入:

[
  {
    "list": [ "item1" ]
  }
]

期望输出:

[
  {
    "list": [
      {
        "listType": "1",
        "listValue": "item1"
      }
    ]
  }
]

补充场景

场景1:非空list + 其他属性

输入:

[
  {
    "list": [ "item1" ],
    "attribute2": "abc"
  }
]

输出:

[
  {
    "list": [
      {
        "listType": "1",
        "listValue": "item1"
      }
    ],
    "attribute2": "abc"
  }
]

场景2:空list + 其他属性

输入:

[
  {
    "list": [],
    "attribute2": "abc"
  }
]

输出:

[
  {
    "list": [],
    "attribute2": "abc"
  }
]

场景3:无list属性

输入:

[
  {
    "attribute2": "abc"
  }
]

输出:

[
  {
    "attribute2": "abc"
  }
]

解决方案JOLT规范

以下规范可满足所有需求:

[
  // 第一步:保存原始list,同时处理非空list的转换,保留其他属性
  {
    "operation": "shift",
    "spec": {
      "*": {
        "list": "[&1].originalList",
        "list": {
          "*": {
            "#1": "[&3].processedList[&1].listType",
            "@(0)": "[&3].processedList[&1].listValue"
          }
        },
        "*": "[&1].&"
      }
    }
  },
  // 第二步:根据原始list的状态生成最终的list字段
  {
    "operation": "shift",
    "spec": {
      "*": {
        "originalList": {
          // 处理空数组情况,直接保留空list
          "[]": {
            "@": "[&3].list"
          },
          // 处理非空数组或null,使用转换后的processedList(null会被转为数组)
          "*": {
            "@(2,processedList)": "[&4].list"
          }
        },
        // 保留所有其他属性
        "*": "[&1].&"
      }
    }
  },
  // 第三步:清理临时字段
  {
    "operation": "remove",
    "spec": {
      "*": {
        "originalList": "",
        "processedList": ""
      }
    }
  }
]

规范说明

  1. 第一步shift操作:

    • 将原始list保存到临时字段originalList,用于后续判断
    • 对非空list的每个元素进行转换,生成包含listType和listValue的对象数组,存入临时字段processedList
    • 保留所有其他原始属性
  2. 第二步shift操作:

    • 检查originalList:若为空数组,直接将空数组赋值给最终的list字段;若为非空数组或null,则将processedList的值赋值给list(null会被自动转为数组)
    • 无originalList时,不会生成list字段,符合需求
  3. 第三步remove操作:清理临时字段originalList和processedList,得到最终结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 01:55:35