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

请求编写Jolt规则:筛选name与token值相同的JSON记录并排序

Jolt过滤与排序规则实现

输入JSON

[
  {
    "id": "1",
    "name": "a",
    "token": "x"
  },
  {
    "id": "2",
    "name": "b",
    "token": "xx"
  },
  {
    "id": "3",
    "name": "xxx",
    "token": "xxx"
  }
]

期望输出(过滤后)

[
  {
    "id": "3",
    "name": "xxx",
    "token": "xxx"
  }
]

需求说明

仅保留JSON数组中name字段与token字段值相同的记录,并实现过滤后按name字段值降序排序。


1. 基础过滤Jolt规则

使用filter操作筛选符合条件的记录:

[
  {
    "operation": "filter",
    "spec": {
      "*": {
        "name": ["=", "@(1,token)"]
      }
    }
  }
]
  • filter操作:遍历数组中的每个元素
  • *:匹配数组的所有元素
  • ["=", "@(1,token)"]:判断当前元素的name值是否等于同层级的token值(@(1,token)表示向上1级的token字段),满足条件的元素将被保留。

2. 过滤+降序排序完整Jolt规则

在过滤后添加sort操作实现降序排序:

[
  {
    "operation": "filter",
    "spec": {
      "*": {
        "name": ["=", "@(1,token)"]
      }
    }
  },
  {
    "operation": "sort",
    "spec": {
      "*": {
        "name": "desc"
      }
    }
  }
]
  • sort操作:对过滤后的数组进行排序
  • "name": "desc":指定按name字段进行降序排序,若需升序可改为"asc"。

效果验证

如果输入数组存在多条符合条件的记录(例如添加{"id":"4","name":"zzz","token":"zzz"}),输出会按name降序排列为:

[
  {
    "id": "4",
    "name": "zzz",
    "token": "zzz"
  },
  {
    "id": "3",
    "name": "xxx",
    "token": "xxx"
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 12:16:11