Skip to content Skip to sidebar Skip to footer

Checking If Json Value Is Empty

I tried all the methods I found on SO but none is working for me The JSON in question (trimmed) json_data = requests.post(api_url, self.build_payload().json() { 'gmetadata':[

Solution 1:

You're misunderstanding how in works. in checks to see if a key exists in a dictionary, it does not index into a dictionary. That's what the square brackets do.

if 'title_jpn' in json_data['gmetadata'][0] is not "":

The above line will not evaluate as you expect. It should be.

if json_data['gmetadata'][0]['title_jpn'] is not "":

This can be further simplified because empty strings '' always evaluate to False in python. So instead of checking if the string is not empty, just check if it has any value at all like the following:

if json_data['gmetadata'][0]['title_jpn']:

If you're trying to guard against the fact that title_jpn might be optional and not always exist, you need to do two conditions in your if statement (which I think is what you were originally trying to do):

if 'title_jpn' in json_data['gmetadata'][0] and json_data['gmetadata'][0]['title_jpn']:

The above line first checks if the title_jpn key is present before trying to check if it's value is empty. This can be further simplified using the dictionary .get() method which allows you to supply a default.

if json_data['gmetadata'][0].get('title_jpn', None):

The above will check if title_jpn is in the dictionary and return the value if it does, or None as a default if it does not. Since None is interpreted as False in python, the if block will not run, which is the desired behaviour.

dict.get(key, default=None)

However, since .get() automatically sets the default value to None, you can simply do the following.

if json_data['gmetadata'][0].get('title_jpn'):

Solution 2:

Your .get won't work, since this applies to dictionaries. As far as I know, "In" won't work either since this is the syntax for a For loop. Probably you want the "Find" method, since this matches a substring within a longer string (which is your goal, if I understand correctly). It'll return minus one if the string isn't found. So in your case, example use:

if json_data['gmetadata'][0].find('title_jpn') != -1:

Solution 3:

My mistake was not inside the method, but outside. You can't know because I didn't post this, but

await self.pm.clientWrap.send_message(self.name, message_object.channel, self.build_title_string(
                json_data) + "\n" + self.build_title_jpn_string(json_data) + "\n")

was producing the error. build_title_jpn_string() would return none but trying to concenate it with the string-title produced the error.

I fixed this by returning an empty string when the if was not hit.


Post a Comment for "Checking If Json Value Is Empty"