如何使用JOLT将含列表的JSON项拆分为多个独立项?
JOLT数组展开与字段匹配解决方案
原始输入
[ { "itemId": "001", "region": "North", "cume": [ 150, 200, 300, 360 ], "type": [ "total", "app", "web", "registered" ] }, { "itemId": "002", "region": "South", "cume": [ 1000, 1200, 3500, 6200 ], "type": [ "total", "app", "web", "registered" ] } ]
期望输出
[ { "cume": 150, "region": "North", "type": "total" }, { "cume": 200, "region": "North", "type": "app" }, { "cume": 300, "region": "North", "type": "web" }, { "cume": 360, "region": "North", "type": "registered" }, { "cume": 1000, "region": "South", "type": "total" }, { "cume": 1200, "region": "South", "type": "app" }, { "cume": 3500, "region": "South", "type": "web" }, { "cume": 6200, "region": "South", "type": "registered" } ]
问题分析
你之前的JOLT规则存在两个核心问题:
- 通配符
*s匹配cume和type后,用[&1]作为新数组索引,会导致不同顶层对象的同索引元素被合并到同一位置,进而让region字段重复赋值成数组。 - 未建立
cume和type数组元素的一一对应关系,无法生成独立的键值对对象。
正确JOLT规则
[ { "operation": "shift", "spec": { "*": { "cume": { "*": { "@": "[].cume", "@(2,region)": "[].region", "@(2,type[&1])": "[].type" } } } } } ]
规则说明
*:遍历原始数组中的每个顶层对象。cume:针对每个对象的cume数组进行处理。*:遍历cume数组的每个元素,&1代表当前元素的索引。@:将当前cume元素值赋值给新对象的cume字段。@(2,region):向上回溯2层,获取当前顶层对象的region值,赋值给新对象的region字段。@(2,type[&1]):向上回溯2层,获取当前顶层对象type数组中与cume元素同索引的元素值,赋值给新对象的type字段。[]:每次处理都会生成一个新的数组元素,自动将所有独立对象拼接成最终的数组结构。
内容的提问来源于stack exchange,提问作者ysh_115
相关产品推荐
相关产品推荐

