如何在 jsonpath-plus 中使用三元运算符使用多个 if else 条件?

How to use multiple if else conditions using ternary operator in jsonpath- plus?

JSON

{
   "customer":{
      "address":{
         "stateRegion":"",
         "stateRegionCode":""
      }
   }
}

代码

"address.state_code": "$.customer.address.[stateRegion ? stateRegion: stateRegionCode?stateRegionCode: null]",

在上面的表达式中,如果它作为父对象出现在客户中,地址作为子对象出现,我希望 stateRegion 作为值,否则我希望 stateRegionCode,如果两者都不存在present 我想要 null,我们如何使用 jsonpath-plus 自定义这个东西?

您不能在对象的初始创建期间执行此操作,因为访问对象的属性(用于您的条件表达式)需要该对象已经存在。

也许你能得到的最接近的是,一旦你定义了对象,写一些类似于你的"address.state_code": "$.customer.address.[stateRegion ? stateRegion: stateRegionCode?stateRegionCode: null]":

的东西

const
  $ = { "customer" : { "address" : { "stateRegion" : "", "stateRegionCode" : "" } } },
  {stateRegion, stateRegionCode} = $.customer.address; // Destructures address
$.customer.address.state_code = stateRegion
  ? stateRegion
  : stateRegionCode
    ? stateRegionCode
    : null;

console.log($.customer.address);