JSONata - am I missing something?

I have a simple JSON

{
  "customers": [
    {
      "id": "XYZ-ABC-DEF",
      "data": {
        "locations": [
          {
            "location_id": 1,
            "location_name": "Main",
            "location_attr": "blue"
          },
          {
            "location_id": 2,
            "location_name": "Secondary"
          }
        ]
      }
    }
  ]
}

I do a simple op:

customers[][data.locations.location_attr = "blue"]

And it works, returns the entire 'customer' object. But only as long as only one record has the "location_attr" field. As soon as I add "location_attr" to a second record - it stops working.

But a different op is still possible:

customers.data.locations[location_attr = "blue"]

However, this defeats the purpose - I need the customer id.

It's driving me nuts :slight_smile: Please point me to the explanation/solution!

What about this:

customers.data.locations[location_attr = "blue"].$$

And possibly:

customers.data.locations[location_attr = "blue"].$$.customers.id

To only get the id.

Please, don't ask for an explanation... but $$ and $ are "magical" (at least for me) in Jsonata.

Thanks! Your suggestion looked promising, but matches the whole structure :frowning: I need only the customer with the attribute.

So it looks like a limitation :frowning:

I had to get rid of embedded structures and add redundancy to the data.

Using your json, what exact output do you need?

Just stumbled upon your jsonata riddle.

Here is the solution I think:

customers[][data.locations.location_attr[$="blue"]!=[]]

you can check it with following url: https://try.jsonata.org/LimnK1l7D

Explanation:
It returns all customers matching function :

data.locations.location_attr[$="blue"] != []
  • The left part (data.locations.location_attr[$="blue"]) of the function creates an array of all location_attr values belonging to that customer that have value "blue".
  • The right part ([]) is an empty array.
2 Likes

Thank you so much! So it looks like this '$' is indeed the magic bullet.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.