Return integer or string instead of None from a JMESPath query

Return integer or string instead of None from a JMESPath query

Problem Description:

Is there a way to return an integer or a string instead of None?
I know that I can do an additional check like:

item = {"SX": {"BX": 1}}

value = jmespath.search("SX.BX", item) if jmespath.search("SX.BX", item) else 0

but the condition is very long and I would like to make it easier.

Solution – 1

You can build that logic in your JMESPath query:

SX.BX || `0`

Given the empty JSON:

{}

Would yield you 0, as you are excepting it.


So, you Python code becomes:

value = jmespath.search("SX.BX || `0`", item)
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject