K Stroud
K Stroud

Reputation: 53

jmespath: Differentiate between a key not found and a key having a null value

I am using the jmespath module in python to search through a nested dictionary.

The problem I am running into is that I want to raise an exception if the key is not found in the dictionary. However, some of the keys have None values, which is completely valid. In both cases where jmespath finds a key with a None value, or does not find a key, it returns None.

Is there any way to differentiate between the two? As far as I can tell, jmespath has no equivalent to a "function." Thanks!

Upvotes: 2

Views: 6466

Answers (1)

Sunitha
Sunitha

Reputation: 12015

There was a detailed discussion about this issue here - https://github.com/jmespath/jmespath.py/issues/113

The outcome is to use contains to check if the key exists

So to check if foo.bar exists in a nested dict, you can use search with arg "contains(keys(foo), 'bar')"

>>> print (jmespath.search('foo.bar', {'foo': {'bar': None}}))
None
>>> jmespath.search("contains(keys(foo), 'bar')", {'foo': {'bar': None}})
True
>>> jmespath.search("contains(keys(foo), 'bar2')", {'foo': {'bar': None}})
False

Upvotes: 3

Related Questions