Jolt转换时attrs数组单元素转为对象的问题及修正需求
Jolt转换问题修正:确保attrs始终以数组形式呈现
问题背景
现有包含JSON数组attrs的JSON数据,attrs内的name/value对数量动态变化,但必含orderType和paymentType两个键值对。当前用Jolt将这两个字段提取至最外层时,出现以下异常:
- 仅含两个预期键值对时,转换后
attrs消失,符合预期; - 多1个额外键值对时,转换后
attrs由数组变为对象,不符合预期; - 多多个额外键值对时,转换后
attrs仍为数组,符合预期。
需求:只要attrs存在,无论剩余几个元素,都强制以数组形式呈现。
原Jolt Spec:
[ { "operation": "shift", "spec": { "*": { "*": "[&1].&", "attrs": { "*": { "name": { "*": { "@2": "[&5].&4" }, "orderType": { "@(2,value)": "[&5].&1" }, "paymentType": { "@(2,value)": "[&5].&1" } } } } } } } ]
修正后的Jolt Spec
[ // 提取目标字段到外层,同时将非目标字段存入attrs数组 { "operation": "shift", "spec": { "*": { "*": "[&1].&", "attrs": { "*": { "name": { "orderType|paymentType": { "@(2,value)": "[&5].&1" }, "*": { "@2": "[&5].attrs[]" } } } } } } }, // 强制attrs为数组(防止单个元素时被转为对象) { "operation": "modify-overwrite-beta", "spec": { "*": { "attrs": ["=toList"] } } }, // 移除空的attrs数组(仅含两个目标字段时触发) { "operation": "remove", "spec": { "*": { "attrs": { "": "" } } } } ]
关键调整说明
- Shift阶段强制数组结构:
用attrs[]替代原&4,明确要求Jolt将非目标字段存入数组,哪怕只有一个元素,避免自动扁平化为对象。 - Modify阶段双重保障:
通过=toList函数,确保即使出现单个对象的极端情况,也会被转为数组。 - Remove阶段清理空数组:
当原attrs仅包含orderType和paymentType时,转换后的attrs会是空数组,这一步将其移除,符合预期。
测试示例
场景2输入(1个额外字段)
[ { "id": "123", "attrs": [ {"name": "orderType", "value": "offline"}, {"name": "paymentType", "value": "wechat"}, {"name": "remark", "value": "test"} ] } ]
转换后输出
[ { "id": "123", "orderType": "offline", "paymentType": "wechat", "attrs": [ {"name": "remark", "value": "test"} ] } ]
内容的提问来源于stack exchange,提问作者sturaw
相关产品推荐
相关产品推荐

