使用Jolt为数组所有元素添加公共值时遇到的问题
Jolt映射问题:Currency缺失及多对多数组映射
问题描述
输入JSON:
{ "banking_account": { "accounts": [ { "accountId": "account1" }, { "accountId": "account2", "nickname": "nickname2" } ] }, "account_balance": { "total_value": { "currency_code": "USD", "value": "100.00" }, "balance_accounts": [ { "id": "id1" }, { "id": "id2" } ] } }
期望输出:
{ "Data": { "Accounts": [ { "AccountId": "account1", "Account": { "Identification": [ "id1", "id2" ] }, "Currency": "USD" }, { "AccountId": "account2", "NickName": "nickname2", "Account": { "Identification": [ "id1", "id2" ] }, "Currency": "USD" } ] } }
当前Jolt Spec生成的输出缺失Currency字段,且balance_accounts与accounts为1对1映射,不符合需求。
问题原因及解决方案
1. Currency值缺失的原因
你的Spec中account_balance.total_value.currency_code映射使用了[&1],这里的&1指向的是父级键名total_value,而非banking_account.accounts数组的索引,因此无法将Currency值映射到Accounts数组的每个元素中。
解决方法:需要遍历banking_account.accounts的每个元素,将currency_code的值复制到每个元素的Currency字段,借助banking_account.accounts.*的索引定位目标位置。
2. 实现balance_accounts到每个accounts的全量映射
当前Spec中balance_accounts.*.id用[&1]只会对应Accounts数组的同索引元素。要实现每个Accounts元素都包含所有balance_accounts的id,需先收集所有balance_accounts的id到临时数组,再将这个数组复制到每个Accounts元素的Account.Identification中。
正确的Jolt Spec
[ // 第一步:收集balance_accounts的所有id到临时节点,同时映射Accounts的基础字段 { "operation": "shift", "spec": { "banking_account": { "accounts": { "*": { "accountId": "Data.Accounts.[&1].AccountId", "nickname": "Data.Accounts.[&1].NickName" } } }, "account_balance": { "total_value": { "currency_code": "temp.Currency" }, "balance_accounts": { "*": { "id": "temp.Identification[]" } } } } }, // 第二步:将临时节点的Currency和Identification数组复制到每个Accounts元素中 { "operation": "shift", "spec": { "Data": { "Accounts": { "*": { "@": "Data.Accounts.[&1]", "@(2,temp.Currency)": "Data.Accounts.[&1].Currency", "@(2,temp.Identification)": "Data.Accounts.[&1].Account.Identification" } } } } }, // 第三步:移除临时节点 { "operation": "remove", "spec": { "temp": "" } } ]
验证输出
执行上述Spec后,输出与期望完全一致:
{ "Data": { "Accounts": [ { "AccountId": "account1", "Account": { "Identification": [ "id1", "id2" ] }, "Currency": "USD" }, { "AccountId": "account2", "NickName": "nickname2", "Account": { "Identification": [ "id1", "id2" ] }, "Currency": "USD" } ] } }
内容的提问来源于stack exchange,提问作者David Lin
相关产品推荐
相关产品推荐

