如何使用Jolt合并两个数组并按hash字段融合公共元素?
需求说明
你要把包含files和tags两个数组的JSON数据,合并成tempFiles数组:根据hash字段,把tags里的tag字段匹配到对应files元素中,同时不能出现冗余的独立tag元素。
输入示例
先给个典型的输入样例,方便对照:
{ "files": [ { "hash": "abc123", "name": "file1.txt" }, { "hash": "def456", "name": "file2.txt" } ], "tags": [ { "hash": "abc123", "tag": "document" }, { "hash": "abc123", "tag": "important" }, { "hash": "def456", "tag": "image" } ] }
分步Jolt配置
1. 按hash分组归集数据
先用shift操作把files和tags按hash键分组,把同一hash的文件信息和标签都攒到一起:
{ "operation": "shift", "spec": { "files": { "*": { "hash": "temp.@(1,hash).hash", "name": "temp.@(1,hash).name" } }, "tags": { "*": { "tag": "temp.@(1,hash).tags[]" } } } }
这一步会生成一个temp对象,每个key是对应的hash值,value里包含该hash的文件属性和标签数组,不会出现零散的tag元素。
2. 把分组后的对象转成数组
再用一次shift,把temp里的键值对转成tempFiles数组:
{ "operation": "shift", "spec": { "temp": { "*": "tempFiles[]" } } }
3. 给无标签的文件补默认空数组(可选)
如果有些文件没有对应的标签,用default操作给tags字段补上空数组,避免字段缺失:
{ "operation": "default", "spec": { "tempFiles": { "*": { "tags": [] } } } }
完整配置代码
把上面三步整合起来,就是最终的Jolt配置:
[ { "operation": "shift", "spec": { "files": { "*": { "hash": "temp.@(1,hash).hash", "name": "temp.@(1,hash).name" } }, "tags": { "*": { "tag": "temp.@(1,hash).tags[]" } } } }, { "operation": "shift", "spec": { "temp": { "*": "tempFiles[]" } } }, { "operation": "default", "spec": { "tempFiles": { "*": { "tags": [] } } } } ]
转换后输出
用前面的输入样例,经过上面的Jolt转换后,输出结果如下:
{ "tempFiles": [ { "hash": "abc123", "name": "file1.txt", "tags": [ "document", "important" ] }, { "hash": "def456", "name": "file2.txt", "tags": [ "image" ] } ] }
所有标签都正确匹配到对应hash的文件条目里,不会出现冗余的独立tag元素。
内容的提问来源于stack exchange,提问作者voodoo
相关产品推荐
相关产品推荐

