JOLT Shift转换:按属性内部值筛选typeName为'xx'的JSON项
JOLT递归过滤typeName为'xx'的节点并收集结果
需求说明
从嵌套JSON结构中提取所有type.typeName等于xx的节点,组成数组,同时移除节点内部的item字段。
输入JSON
{ "id": 11, "item": [ { "id": "11_1", "action": "add", "type": { "id": "11_1_xx", "typeName": "xx" }, "item": [ { "id": "11_1_1", "action": "add", "type": { "id": "11_1_1_zz", "typeName": "zz" }, "item": [ { "id": "11_1_1_1", "action": "add", "type": { "id": "11_1_1_1_xx", "typeName": "xx" } } ] }, { "id": "11_1_2", "action": "add", "type": { "id": "11_1_2_xx", "typeName": "xx" }, "item": [ { "id": "11_1_2_1", "action": "add", "type": { "id": "11_1_2_1_zz", "typeName": "zz" } } ] } ] } ] }
期望输出JSON
[ { "id": "11_1", "action": "add", "type": { "id": "11_1_xx", "typeName": "xx" } }, { "id": "11_1_1_1", "action": "add", "type": { "id": "11_1_1_1_xx", "typeName": "xx" } }, { "id": "11_1_2", "action": "add", "type": { "id": "11_1_2_xx", "typeName": "xx" } } ]
JOLT转换Spec
[ { "operation": "shift", "spec": { "item": { "*": { "@": "temp[]", "item": { "*": { "@": "temp[]", "item": { "*": { "@": "temp[]" } } } } } } } }, { "operation": "shift", "spec": { "temp": { "*": { "type": { "typeName": { "xx": { "@2,id": "[#4].id", "@2,action": "[#4].action", "@2,type": "[#4].type" } } } } } } }, { "operation": "remove", "spec": { "*": { "": "" } } } ]
转换说明
- 第一步(shift):递归遍历所有层级的
item节点,将每个节点存入根级temp数组,确保所有可能的节点都进入筛选范围。 - 第二步(shift):遍历
temp数组,仅保留type.typeName为xx的节点,提取节点的id、action、type字段,排除item字段。 - 第三步(remove):清理转换过程中生成的空对象,保证输出数组整洁。
内容的提问来源于stack exchange,提问作者Michal
相关产品推荐
相关产品推荐

