Set null value in ternary operator in JMESPath?

Is there a way to set a value to null with JMESPath? In my example, the value should be set to null if qux_1 is not null and else the value should be set to the value of baz.

I thought the ternary operator could be read as if else condition but null would be evaluated as false?

import jmespath

o = {
    "foo": {
        "bar": {"baz": 4321},
        "bar_1": {"baz_1": {"qux_1": 1234}},
    }
}
jmespath.search("(foo.bar_1.baz_1.qux_1 && null)||foo.bar.baz", o)

>Solution :

The issue in your actual attempt is that null || `some_value` will always yield some_value, because null is a falsy value (evaluates to false in a condition).


What you can do, here is to use a filter projection.
But, for that, you first need to have an array — which can be done via the function to_array.

Then, you just have to display foo.bar.baz if foo.bar_1.baz_1.qux_1:

to_array(@)[?foo.bar_1.baz_1.qux_1].foo.bar.baz

To come back to a single value, you’ll need to stop the projection, then take the first element of the resulting array:

to_array(@)[?foo.bar_1.baz_1.qux_1].foo.bar.baz | [0]

Mind that this is a simple syntax, that could have some gotcha, e.g. if foo.bar_1.baz_1.qux_1 == false or foo.bar_1.baz_1.qux_1 == null, and then you need to adapt your condition to your exact use case:

For example:

to_array(@)[?foo.bar_1.baz_1.qux_1 != null].foo.bar.baz | [0]

Leave a Reply