Search code examples
jsonjmespath

How to differentiate null and false in JMESPath?


From a JSON object, I want to return true if a key is missing, false otherwise.
How to achieve this?

  1. First case, the key is defined: And the value is false

    {"my_key": false}
    

    The expression my_key will return false.

    And the value is a number:

    {"my_key": 123}
    

    The expression my_key will return 123.

  2. Second case:

    {"my_other_key": false}
    

    The expression my_key would now return null.

I need an expression which would work with both cases, returning false (or other values) in the first case and true in the second one.

The built-in function not_null could be good, but, it treats false and null equally.


Solution

  • The expression you are looking for would uses a conditional "or" and can be expressed this way:

    my_key == null || my_key
    

    Simply put, it tells JMESPath to return either

    • the result of the test my_key == null, which would be true only if the value of my_key is strictly equal to null
    • or — so, if the test my_key == null result in a false — the value of my_key

    Using it on:

    • the JSON object
      {"my_key": false}
      
      Would return false
    • the JSON object
      {"my_key": 123}
      
      Would return 123
    • the JSON object
      {"my_other_key": false}
      
      Would return true