1

I have an array of objects like so:

{
    "openingDates": [
        {
            "location": "Main St.",
            "openingDate": "2023-01-09T00:00:00Z"
        },
        {
            "location": "Northwood Park",
            "openingDate": "2006-01-10T00:00:00Z"
        }
    ]
}

I have an expression to sort by openingDate then get the openingDate value:

sort_by(openingDates, &openingDate)[0].openingDate

However, openingDates can potentially be null, which will obviously cause an error if I try to run a sort on it. Is there a way to prevent the sort in my expression if the value is null?

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
mortimerfreeze
  • 199
  • 1
  • 1
  • 9

1 Answers1

1

The issue is coming from the fact that sort_by will only accept the first parameter to be an array.

This say, the to_array function can help you do an array of your null value, as to_array(null) will give you [null].
And, with an array containing null, your further query would return you a null for the openingDate, as expected.

So, given

{}

And the query

sort_by(to_array(openingDates), &openingDate)[0].openingDate

This will yield

null

And will still give

"2006-01-10T00:00:00Z"

On your example object.

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
  • Yes I tested the expression on the jmespath.org website and it looks like it is valid. Would the case be the same when running it in something like Java code? Looks like I get an error: `io.burt.jmespath.function.ArgumentTypeException: Invalid argument type calling "sort_by": expected array of object but was null` – mortimerfreeze Jan 19 '23 at 17:55
  • I tested with the Python implementation, it should do for the others, but let me have a look, at the Java one, then. – β.εηοιτ.βε Jan 19 '23 at 18:33
  • Did you look at this chapter of the project, though: https://github.com/burtcorp/jmespath-java#configuration – β.εηοιτ.βε Jan 19 '23 at 18:35
  • This jmespath java configuration doc is exactly what I needed! – mortimerfreeze Jan 20 '23 at 20:22