You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 19:24:02