Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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]
like image 963
john Avatar asked Oct 11 '16 19:10

john


People also ask

Does JSON allow empty string?

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 .

Is empty string null in JSON?

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.

How do you check if a JSON object is empty or not?

Using JSON. If we stringify the object and the result is simply an opening and closing bracket, we know the object is empty.


1 Answers

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 ''
like image 68
Zaur Nasibov Avatar answered Sep 25 '22 16:09

Zaur Nasibov