Search code examples
jsonata

How to deal with an empty array when filtering?


If I have this input

[
  {
    "data": 4
  },
  {
    "data": 7
  }
]

and the expression $.data[], I get [4, 7].

If the input array is empty instead [], I get no match.

I want an expression which keeps the result the same in the first example, but returns an empty array [] in the second example. How can I do that?


Solution

  • [data] will do the trick.

    In your expression $.data[], the spare brackets after data are actually an empty filter. Also, you can skip the leading "$.".

    This leaves us with "data", which returns no match when applied to an empty array. Surrounding data with square brackets changes that to returning [] while not adding an extra array in case data returns [4, 7]