如何在jsonpath-plus中使用三元运算符实现多if else条件取值?
实现方案
你需要的逻辑可以通过jsonpath-plus支持的三元嵌套表达式实现,正确写法如下:
"address.state_code": "$.customer.address ? (@.stateRegion ? @.stateRegion : (@.stateRegionCode ? @.stateRegionCode : null))"
如果你需要把空字符串也判定为「无有效值」走降级逻辑,可以加上非空判断:
"address.state_code": "$.customer.address ? (@.stateRegion && @.stateRegion !== '' ? @.stateRegion : (@.stateRegionCode && @.stateRegionCode !== '' ? @.stateRegionCode : null))"
逻辑说明
- 表达式中用
@指代当前定位到的customer.address对象,无需额外添加多余的括号包裹属性判断逻辑 - 第一层判断优先取
stateRegion的值,符合条件直接返回 - 第一层判断不满足时进入第二个三元判断,取
stateRegionCode的值 - 两个字段都不符合判断条件时最终返回
null
常见调整说明
如果customer或者address节点可能不存在,可以在最外层加一层兜底判断,避免取值报错:
"address.state_code": "$.customer?.address ? (@.stateRegion ? @.stateRegion : (@.stateRegionCode ? @.stateRegionCode : null)) : null"
内容的提问来源于stack exchange,提问作者theBeginner
相关产品推荐
相关产品推荐

