kvtral
kvtral

Reputation: 33

How to retrieve a specific value using JSONPath with logical OR condition?

I have a JSON structure that may change a key:

{
  "status": "ONLINE",
  "meter": "A123",
  "date": "2024-02-28T14:51:12"
}

OR

{
  "status": "ONLINE",
  "crew": "XMS-858",
  "date": "2024-02-28T15:05:19"
}

I need help to structure a JSONPath expression to obtain the value corresponding to the 'meter' key or the 'crew' key depending on which exists in the json

I tried this:

$.[?(@.meter || @.crew)]

which works (the OR expression) but it brings me the full level of where the key is found

[
   {
      "status": "ONLINE",
      "crew": "XMS-858",
      "date": "2024-02-28T15:05:19"
   }
]

So, i tried a different approach. This one works better:

$.['meter', 'crew']

But with this, i got the key-value pair

{
   "crew": "XMS-858"
}

And I just need the value, i tried a lot of differents ways but with no success,

Someone has an idea?

Upvotes: 0

Views: 187

Answers (1)

gregsdennis
gregsdennis

Reputation: 8428

jsonpath $.['meter', 'crew']

But with this, i got the key-value pair

json { "crew": "XMS-858" }

This isn't what I'd expect, and it's not what my implementation does (https://json-everything.net/json-path.

Pedantically, $.['meter', 'crew'] isn't valid: you need to remove the .:

$['meter', 'crew']

The spec RFC 9535 was recently released, and most implementations haven't adopted it yet. As such, many implementations support their own flavor, so you'll need to check with them for specifics.

On my implementation (which is compliant), this returns

[
  {
    "Value": "A123",
    "Location": "$['meter']"
  }
]

(My implementation gives both the value and where it appears in the data.)

Upvotes: 1

Related Questions