如何调整Jolt脚本将stats数组展开至顶层并避免值转为数组?
问题:展开JSON中的stats数组并关联父对象字段
原始JSON数据:
[ { "id": 1015380, "type": "campaign", "stats": [ { "month": "2023-07", "spent": "3116.90", "impressions": 17783, "clicks": 78 }, { "month": "2023-08", "spent": "1490.36", "impressions": 6721, "clicks": 17 } ] }, { "id": 1015695, "type": "campaign", "stats": [ { "month": "2023-08", "spent": "1490.36" } ] } ]
需求:将stats数组展开到顶层,每个stats子对象与对应父对象的id、type字段组合成独立对象。原Jolt脚本执行后会把stats中的值存储为数组,无法得到预期的扁平结构。
解决方案:修正后的Jolt脚本
原脚本的问题在于使用了[&3]复用父级数组索引,导致同一父对象下的多个stats项被塞进同一个数组位置。需要改用[&1]基于stats数组的当前索引生成新的顶层对象,同时正确关联父对象的id和type字段。
修正后的Jolt脚本:
[ { "operation": "shift", "spec": { "*": { "stats": { "*": { "@(2,id)": "[&1].id", "@(2,type)": "[&1].type", "*": "[&1].&" } } } } } ]
脚本说明:
@(2,id)和@(2,type):向上回溯2层,获取父对象的id和type值[&1]:基于当前stats数组的索引生成新的顶层数组元素,确保每个stats项对应一个独立的顶层对象"*": "[&1].&":将stats子对象的所有字段直接映射到新对象中
预期输出结果
[ { "id": 1015380, "type": "campaign", "month": "2023-07", "spent": "3116.90", "impressions": 17783, "clicks": 78 }, { "id": 1015380, "type": "campaign", "month": "2023-08", "spent": "1490.36", "impressions": 6721, "clicks": 17 }, { "id": 1015695, "type": "campaign", "month": "2023-08", "spent": "1490.36" } ]
内容的提问来源于stack exchange,提问作者fujidaon
相关产品推荐
相关产品推荐

