david david - 9 days ago 4x
JSON Question

How to return empty string if property doesn't exist in the JSON string?

I have a JSON string from which I am trying to extract a property value using Python as shown below:

def extract_property(node, to_extract):
data, stat = zk.get(node)
jsonString = data.decode("utf-8")
jStr = json.loads(jsonString)
return jStr[to_extract]

Now it is possible, the property value that I am trying to extract doesn't exist in that JSON string so it will fail. How can I return empty string if property doesn't exist at all in the JSON string.

This line can fail if property doesn't exist.

return jStr[to_extract]


Simply use dict.get(), i.e.:

return jStr.get(to_extract, '')

See https://docs.python.org/3/library/stdtypes.html#dict.get for more details.


Thanks to @jez for pointing out, that jStr is not guaranteed to be a dictionary. However, the result for JSON parsing is known: if it's not a dictionary, then it's a list, number or a string. In this case, wrap it into a type checking routine, e.g.:

    return jStr[to_extract]
except (KeyError, AttributeError):
    return ''