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

669 views Asked by At

JSON

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

Code

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

Here in the above expression , I want stateRegion as the value if it is present in customer as parent object and address as a child object , else I want stateRegionCode and if both are not present I want null, how can we customize this thing using jsonpath-plus?

1

There are 1 answers

2
Cat On BEST ANSWER

You can't do this during the initial creation of the object because accessing the object's properties (for use in your conditional expression) requires that the object already exists.

Maybe the closest you can get is, once you've defined the object, to write something similar to your "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);