如何在NiFi中用JOLT Transform将嵌套数值数组合并为目标数组
Apache NiFi JOLT 数据转换实现
需求
将输入JSON中嵌套的两组数值数组合并为单个对象数组,每个对象需包含:
- 两组数组的对应值(重命名为
a_value、t_value) - 关联的
name字段 row与column拼接后的sp字段
同时保留顶层的fn、idc、sop字段。
输入JSON
{ "md": { "fn": "abcd" }, "content": { "idc": "0", "lsr": "3", "lsc": "A", "array Of Arrays": [ { "name": "step_1", "row": "2", "column": "A", "gph": { "a values": [ 0.23, 1.39 ], "t values": [ 0.3, 1.9 ] } }, { "name": "step_2", "row": "3", "column": "A", "gph": { "a values": [ 0.56, 2.49 ], "t values": [ 1.4, 2.8 ] } } ] } }
现有JOLT规则
[ { "operation": "shift", "spec": { "md": { "fn": "fn" }, "content": { "idc": "idc", "lsr": "lsr", "lsc": "lsc", "array Of Arrays": { "*": { "name": "name[]", "s": "s[]", "p": "p[]", "gph": "&[]" } } } } }, { "operation": "modify-default-beta", "spec": { "sop": "=concat(@(2,lsr),@(2,lsc))" } } ]
当前输出
{ "fn" : "abcd", "idc" : "0", "lsr" : "3", "lsc" : "A", "name" : [ "step_1", "step_2" ], "s" : [ "2", "3" ], "p" : [ "A", "A" ], "gph" : [ { "a values" : [ 0.23, 1.39 ], "t values" : [ 0.3, 1.9 ] }, { "a values" : [ 0.56, 2.49 ], "t values" : [ 1.4, 2.8 ] } ], "sop" : "3A" }
期望输出
{ "fn" : "abcd", "idc" : "0", "array" : [ {"name": "step_1", "sp": "2A", "a_value": 0.23, "t_value": 0.3}, {"name": "step_1", "sp": "2A", "a_value": 1.39, "t_value": 1.9}, {"name": "step_2", "sp": "3A", "a_value": 0.56, "t_value": 1.4}, {"name": "step_2", "sp": "3A", "a_value": 2.49, "t_value": 2.8} ], "sop" : "3A" }
修正后的JOLT规则
[ // 展开嵌套数组,关联对应字段与数值数组 { "operation": "shift", "spec": { "md": { "fn": "fn" }, "content": { "idc": "idc", "lsr": "lsr", "lsc": "lsc", "array Of Arrays": { "*": { "name": "temp[&1].name", "row": "temp[&1].row", "column": "temp[&1].column", "gph": { "a values": { "*": "temp[&3].a_values[&1]" }, "t values": { "*": "temp[&3].t_values[&1]" } } } } } } }, // 拼接生成sp和sop字段 { "operation": "modify-default-beta", "spec": { "temp": { "*": { "sp": "=concat(@(1,row),@(1,column))" } }, "sop": "=concat(@(1,lsr),@(1,lsc))" } }, // 将数值对转换为独立对象,整理到array数组 { "operation": "shift", "spec": { "fn": "fn", "idc": "idc", "sop": "sop", "temp": { "*": { "a_values": { "*": { "@2,name": "array[&3].name", "@2,sp": "array[&3].sp", "@": "array[&3].a_value", "@2,t_values[&1]": "array[&3].t_value" } } } } } }, // 清理临时字段与冗余顶层字段 { "operation": "remove", "spec": { "temp": "", "lsr": "", "lsc": "" } } ]
规则说明
- Shift(第一步):把
array Of Arrays中的每个元素拆解,将name、row、column和对应的a values、t values存入临时数组temp,通过索引绑定对应关系。 - Modify:为每个临时元素拼接
sp字段,同时生成顶层的sop字段。 - Shift(第三步):遍历
temp中的每个数值对,将关联的name、sp、a_value、t_value组合成独立对象,统一存入array数组。 - Remove:删除临时数组
temp以及不再需要的lsr、lsc字段。
内容的提问来源于stack exchange,提问作者VKB
相关产品推荐
相关产品推荐

