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]
In Spark 3.0 and above, the JSON parser does not allow empty strings. An exception is thrown for all data types, except BinaryType and StringType .
Yes, JSON has the null value (which is indeed treated as a value, not as the absence of value), and the empty string, and they are different.
Using JSON. If we stringify the object and the result is simply an opening and closing bracket, we know the object is empty.
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.
UPD:
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.:
try:
return jStr[to_extract]
except (KeyError, AttributeError):
return ''
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With