基于Jolt实现根据city字段值动态设置address字段的技术需求
问题描述
源JSON
注:原JSON存在语法错误,已修正"age"字段的冒号缺失问题
{ "name": "test", "age": 10, "city": null, "pinCode": "400081", "address": { "buildingNo": "B-301" } }
转换需求
- 当
city字段值为null时,结果中person.address需设置为null,输出示例:
{ "person": { "name": "test", "age": 10, "address": null } }
- 当
city字段值不为null时,person.address需包含pinCode和原address.buildingNo字段,输出示例:
{ "person": { "name": "test", "age": 10, "address": { "pinCode": "400081", "buildingNo": "B-301" } } }
尝试的Jolt规则(未达到预期)
[ { "operation": "shift", "spec": { "name": "person.name", "age": "person.age", "city": { "null": { "@(1,person.address)": null }, "*": { "@1": "person.address.city" } }, "pinCode": "person.address.pinCode", "address": { "buildingNo": "person.address.buildingNo" } } } ]
正确的Jolt配置
[ { "operation": "shift", "spec": { "name": "person.name", "age": "person.age", "pinCode": "temp.pinCode", "address": { "buildingNo": "temp.buildingNo" }, "city": "city" } }, { "operation": "shift", "spec": { "person": "person", "city": { "null": { "#null": "person.address" }, "*": { "@2,temp": "person.address" } } } }, { "operation": "remove", "spec": { "city": "", "temp": "" } } ]
配置说明
- 第一个
shift操作:提取公共字段name、age到person下,同时将pinCode和buildingNo暂存到temp对象,保留city字段用于后续判断。 - 第二个
shift操作:根据city的值进行分支处理:- 若
city为null,直接将person.address设为null; - 若
city不为null,将暂存的temp对象内容赋值给person.address。
- 若
- 第三个
remove操作:清理临时字段city和temp,得到最终结构。
内容的提问来源于stack exchange,提问作者Ajinkya
相关产品推荐
相关产品推荐

