schosen
schosen

Reputation: 61

How can I get jmespath filter to return true if the value exists and false if it doesn't (python)

This is an extension from a previous question that is unresolved but another way of looking at the problem HERE

{
  "name": "Sarah",
  "region": "south west",
  "age": 21,
  "occupation": "teacher",
  "height": 145,
  "education": "university",
  "favouriteMovie": "matrix",
  "gender": "female",
  "country": "US",
  "level": "medium",
  "tags": [],
  "data": "abc",
  "moreData": "xyz",
  "logging" : {
    "systemLogging" : [ {
      "environment" : "test",
      "example" : [ "this", "is", "an", "example", "array" ]
    } ]
  }
}

If I wanted to see if a value exists for simple key value pairs in a python dictionary I could use the jmespath query to do so

"occupation == `teacher`"
>> True
"occupation == `dancer`"
>> False

But with more complicated data e.g nested dictionaries with lists/arrays the best I can do is filter to obtain the value

"logging.systemLogging[?environment == `test`] | [0].enabled"
>> test
"logging.systemLogging[?environment == `prod`] | [0].enabled"
>> None

How do I get the example above to return True or False rather then the value if it exists and None or empty array [] if it doesn't

Upvotes: 4

Views: 3718

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39294

Well, you can perfectly do the same:

logging.systemLogging[?environment == `test`] | [0].enabled != null

On

{
    "name": "Sarah",
    "region": "south west",
    "age": 21,
    "occupation": "teacher",
    "height": 145,
    "education": "university",
    "favouriteMovie": "matrix",
    "gender": "female",
    "country": "US",
    "level": "medium",
    "tags": [],
    "data": "abc",
    "moreData": "xyz",
    "logging": {
        "systemLogging": [{
            "environment": "test",
            "example": ["this", "is", "an", "example", "array"]
        }]
    }
}

Will result in

false

While the same on this JSON — where logging.systemLogging[0].enabled: false was added:

{
    "name": "Sarah",
    "region": "south west",
    "age": 21,
    "occupation": "teacher",
    "height": 145,
    "education": "university",
    "favouriteMovie": "matrix",
    "gender": "female",
    "country": "US",
    "level": "medium",
    "tags": [],
    "data": "abc",
    "moreData": "xyz",
    "logging": {
        "systemLogging": [{
            "enabled": false,
            "environment": "test",
            "example": ["this", "is", "an", "example", "array"]
        }]
    }
}

Will result in

true

Upvotes: 2

Related Questions