使用JOLT v0.1.1填充JSON数组时Null元素问题求助
JOLT v0.1.1 去除转换后数组前置null的解决方案
问题根源是遍历included数组时,不符合type: "matching-indicators"的元素会生成null占位,最终导致数组开头或中间出现无效的null值。下面给两种直接解决的方案:
方案一:转换时直接过滤符合条件的元素(推荐)
这种方式从源头避免生成null,效率更高。假设你的输入JSON结构类似:
{ "included": [ {"type": "other-type", "name": "x", "label": "X", "score": 0}, {"type": "matching-indicators", "name": "match1", "label": "匹配项1", "score": 85}, {"type": "matching-indicators", "name": "match2", "label": "匹配项2", "score": 92}, {"type": "unrelated", "name": "y", "label": "Y", "score": 50} ] }
使用以下JOLT规范:
[ { "operation": "shift", "spec": { "included": { "*": { "type": { "matching-indicators": { "@(2,name)": "temp[#2].name", "@(2,label)": "temp[#2].label", "@(2,score)": "temp[#2].score" } } } } } }, { "operation": "shift", "spec": { "temp": { "*": "[&1].&" } } } ]
逻辑说明:
- 第一个
shift操作:只针对type等于matching-indicators的元素,提取它的name、label、score到临时数组temp里,不符合条件的元素不会被处理,自然不会生成null。 - 第二个
shift操作:把temp数组的结构整理成你需要的纯净数组格式。
方案二:先生成含null的数组,再移除null
如果你的转换逻辑需要先保留所有数组位置再过滤,可先用modify-overwrite-beta结合removeNulls函数清理null:
JOLT规范:
[ { "operation": "shift", "spec": { "included": { "*": { "type": { "matching-indicators": { "@(2,name)": "[&3].name", "@(2,label)": "[&3].label", "@(2,score)": "[&3].score" } } } } } }, { "operation": "modify-overwrite-beta", "spec": { "*": "=removeNulls" } } ]
逻辑说明:
- 第一个
shift操作:遍历所有included元素,符合条件的提取字段,不符合的位置会生成null。 - 第二个
modify操作:调用removeNulls函数,把数组中所有null元素直接移除,得到纯净的目标数组。
内容的提问来源于stack exchange,提问作者Mariano Baudena
相关产品推荐
相关产品推荐

