如何编写Jolt规格,为嵌套数组对象添加父数组关联属性?
用Jolt实现为嵌套pets对象添加对应ownerName属性
当然可以实现这个需求,以下是对应的Jolt规格以及详细说明:
输入JSON
{ "owners": [ { "ownerId": "1", "ownerName": "Alice" }, { "ownerId": "2", "ownerName": "Bob" } ], "children": [ { "childId": "c1", "pets": [ { "petId": "p1", "ownerId": "1" }, { "petId": "p2", "ownerId": "2" } ] }, { "childId": "c2", "pets": [ { "petId": "p3", "ownerId": "1" } ] } ] }
期望输出JSON
{ "owners": [ { "ownerId": "1", "ownerName": "Alice" }, { "ownerId": "2", "ownerName": "Bob" } ], "children": [ { "childId": "c1", "pets": [ { "petId": "p1", "ownerId": "1", "ownerName": "Alice" }, { "petId": "p2", "ownerId": "2", "ownerName": "Bob" } ] }, { "childId": "c2", "pets": [ { "petId": "p3", "ownerId": "1", "ownerName": "Alice" } ] } ] }
Jolt转换规格
[ { "operation": "shift", "spec": { "owners": "owners", "children": { "*": { "childId": "children[&1].childId", "pets": { "*": { "@": "children[&3].pets[&1]", "@(4,owners[#ownerId].ownerName)": "children[&3].pets[&1].ownerName" } } } } } } ]
规格说明
- 直接保留原有
owners数组的结构映射到输出字段 - 遍历
children数组的每个元素:- 保留
childId的字段映射 - 遍历每个子项的
pets数组:- 用
@将当前pet的所有原有属性映射到对应位置 - 通过
@(4,owners[#ownerId].ownerName)完成关联匹配:4表示向上回溯4层路径,定位到根节点的owners数组#ownerId表示以当前pet对象的ownerId值为索引,从owners数组中取出对应的ownerName
- 用
- 保留
内容的提问来源于stack exchange,提问作者Rock
相关产品推荐
相关产品推荐

