求助:含双层嵌套数组的复杂JSON的Jolt扁平化转换
Jolt转换嵌套JSON:补充date字段实现扁平化数组
问题需求
需要将包含key数组(含date字段)和value数组(嵌套values与orders两层数组)的输入JSON,扁平化为包含date、location、total_capacity、capacity_flag、order_type、consumed_capacity字段的对象数组,现有Jolt Spec无法正确获取date字段。
输入JSON
{ "key": [ { "date": "27/09/2023" } ], "value": [ { "values": [ { "location": "3005", "total_capacity": 24, "capacity_flag": "", "orders": [ { "order_type": "INIT", "consumed_capacity": 0 }, { "order_type": "PUSH", "consumed_capacity": 0 } ] }, { "location": "3007", "total_capacity": 72, "capacity_flag": "", "orders": [ { "order_type": "INIT", "consumed_capacity": 0 }, { "order_type": "PUSH", "consumed_capacity": 0 }, { "order_type": "RPLN", "consumed_capacity": 0 } ] } ] } ] }
期望输出JSON
[ { "date": "27/09/2023", "location": "3005", "total_capacity": 24, "capacity_flag": "", "order_type": "INIT", "consumed_capacity": 0 }, { "date": "27/09/2023", "location": "3005", "total_capacity": 24, "capacity_flag": "", "order_type": "PUSH", "consumed_capacity": 0 }, { "date": "27/09/2023", "location": "3007", "total_capacity": 72, "capacity_flag": "", "order_type": "INIT", "consumed_capacity": 0 }, { "date": "27/09/2023", "location": "3007", "total_capacity": 72, "capacity_flag": "", "order_type": "PUSH", "consumed_capacity": 0 }, { "date": "27/09/2023", "location": "3007", "total_capacity": 72, "capacity_flag": "", "order_type": "RPLN", "consumed_capacity": 0 } ]
尝试的Jolt Spec(date字段无法正确获取)
[ { "operation": "shift", "spec": { "value": { "*": { "values": { "*": { "orders": { "*": { "order_type": "&3.&1.order_type", "consumed_capacity": "&3.&1.consumed_capacity", "@2,location": "&3.&1.location", "@2,total_capacity": "&3.&1.total_capacity", "@2,capacity_flag": "&3.&1.capacity_flag" } } } } } } } }, { // 移除上一步生成的中间对象键 "operation": "shift", "spec": { "*": { "*": "" } } } ]
正确的Jolt Spec
[ { "operation": "shift", "spec": { "value": { "*": { "values": { "*": { "orders": { "*": { "order_type": "&3.&1.order_type", "consumed_capacity": "&3.&1.consumed_capacity", "@2,location": "&3.&1.location", "@2,total_capacity": "&3.&1.total_capacity", "@2,capacity_flag": "&3.&1.capacity_flag", "@(5,key[0].date)": "&3.&1.date" } } } } } } } }, { "operation": "shift", "spec": { "*": { "*": "" } } } ]
关键说明
- 在第一个shift操作中,通过
@(5,key[0].date)引用最外层key数组中的date字段:5表示从当前orders子元素位置向上回溯5层层级(依次到orders、当前values元素、values数组、value数组元素、根节点),从而正确跨层级获取date值。 - 第二个shift操作保持原有逻辑,用于移除中间生成的层级键,将结构扁平化为最终的对象数组。
内容的提问来源于stack exchange,提问作者Thiyagaraj Narayanan
相关产品推荐
相关产品推荐

