Search code examples
javajsonpath

How to use OR condition in JsonPath if one condition is not correct


I can have following JSONs:

{
  "class": [
    {
      "extension": [
        {
          "url": "example.com",
          "valueIdentifier": {
            "value": "myValue"
          }
        }
      ]
    }
  ]
}

or

{
  "class": [
    {
      "extension": [
        {
          "url": "example.com",
          "valueString": "myValue"
        }
      ]
    }
  ]
}

I want to retrieve value or valueString value depending on json. In XPath I can use | operator and engine will take proper value:

/*:class/*:extension[@url='example.com']/*:valueString/@value | /*:class/*:extension[@url='example.com']/*:valueIdentifier/*:value/@value

JsonPath seems to not working that way. I tried a lot of different combination in JsonPath but none of them worked. I use Jayway engine. I tried:

$.class[0].extension[?(@.url=="example.com")].valueString ||
   $.class[0].extension[?(@.url=="example.com")].valueIdentifier.value

$.class[0].extension[?(@.url=="example.com")]['valueString', 'valueIdentifier', 'value']

$.class[0].extension[?(@.url=="example.com")].[?(@.value)].[*]

Anyone know if it is possible to write same (or similar) expression?


Solution

  • Found the answer.

    $.concat($.class[0].extension[?(@.url=="example.com")].[?(@.valueString || @..value)].valueIdentifier.value,$.class[0].extension[?(@.url=="example.com")].[?(@.valueString || @..value)].valueString)
    

    Solution works in Jayway engine in version (at least) 2.7. I tried also on version 2.4 but it didn't work.