Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading