Jolt Spec问题:顶层首个元素被跳过,需修正过滤逻辑
修正Jolt Spec实现过滤需求
需求描述
在与c同级位置新增filtered属性,包含c中enable不为false的元素。
输入JSON
[ { "e": "id1", "c": [ { "title": "title1", "enable": false } ] }, { "e": "id2", "c": [ { "title": "title2", "enable": true } ] } ]
期望输出
[ { "e": "id1", "c": [ { "title": "title1", "enable": false } ], "filtered": [] }, { "e": "id2", "c": [ { "title": "title2", "enable": true } ], "filtered": [ { "title": "title2", "enable": true } ] } ]
原Spec存在的问题
- 使用
modify-default-beta操作错误地将所有c元素中的enable字段强制改为true,篡改了原始数据。 - Shift操作中多余的
root层级导致顶层第一个元素未被正确生成filtered属性。
修正后的Jolt Spec
[ { "operation": "shift", "spec": { "*": { "@": "&", "c": { "*": { "enable": { "false": null, "*": { "@2": "&5.filtered[]" } } } } } } }, { "operation": "modify-default-beta", "spec": { "*": { "filtered": [] } } } ]
修正说明
- Shift操作:
- 遍历顶层数组的每个元素,通过
@": "&"保留所有原始字段。 - 遍历
c数组内的元素,判断enable值:若为false则跳过,否则将整个c元素(@2指向当前元素的上层两层对象)放入当前顶层元素的filtered数组(&5回溯到顶层数组的索引位置)。
- 遍历顶层数组的每个元素,通过
- Modify操作:
- 为所有顶层元素默认设置
filtered为空数组,确保即使c中没有符合条件的元素,也能生成空的filtered属性。
- 为所有顶层元素默认设置
内容的提问来源于stack exchange,提问作者Vishal Patel
相关产品推荐
相关产品推荐

