如何使用Jolt Spec实现JSON对象合并、嵌套数组移除及指定对象清理
Jolt数据合并与数组扁平化实现方案
输入JSON
{ "info": [ {"item": "sugar","price": 4,"state": "Alberta","country": "Canada"}, {"item": "sugar","price": 4.5,"state": "California","country": "US"} ], "location": { "continent": [ {"country": "US","coordinates": {"lang": "97º 00' W","long": "38º 00' N"}}, {"country": "Canada","coordinates": {"lang": "95° 00' W","long": "60° 00' N"}} ] }, "metarecord": {"continent": "North America"} }
需求
- 移除所有嵌套数组,将数据整合成一维对象数组
- 依据
country字段匹配,把location.continent中对应国家的lang、long字段合并到info的对应对象中 - 给
info的每个对象添加metarecord.continent字段值 - 最终剔除
location和metarecord这两个顶层对象
尝试的Jolt Spec(未达到预期)
[ { "operation": "shift", "spec": { "info": { "*": { "item": "[&1].item", "price": "[&1].price", "state": "[&1].state", "country": "[&1].country" } }, "location": { "continent": { "@": "[&1].continent" } }, "metarecord": { "continent": { "*": { "$": "[&2].&1" } } } } } ]
错误输出
[ {"item": "sugar","price": 4,"state": "Alberta","country": "Canada"}, {"item": "sugar","price": 4.5,"state": "California","country": "US"} ]
正确的Jolt Spec
[ { "operation": "shift", "spec": { "info": { "*": { // 保留info对象原有所有字段 "@": "[&1].&", // 引入metarecord的continent字段到当前对象 "@(2,metarecord.continent)": "[&1].continent", // 通过country字段匹配location中对应国家的坐标数据 "@(2,location.continent[#2].coordinates.lang)": "[&1].lang", "@(2,location.continent[#2].coordinates.long)": "[&1].long" } } } } ]
说明
@用于直接保留当前层级的所有字段,避免逐个字段手动映射@(2,metarecord.continent)表示向上遍历2层获取metarecord.continent的值,赋值给当前对象的continent字段@(2,location.continent[#2].coordinates.lang)中#2引用当前info对象的country字段值,以此匹配location.continent数组中对应国家的坐标数据,实现按国家关联合并
内容的提问来源于stack exchange,提问作者kif
相关产品推荐
相关产品推荐

