2

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!

K Stroud
  • 53
  • 1
  • 4

1 Answers1

3

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
Sunitha
  • 11,777
  • 2
  • 20
  • 23