Check Json Data Is None in Python

Check Json data is none in python

You can use data.items() to get key and value AND then you can process according to your demands:-

import json
data = { "a":1, "b":2, "c":3 }
for key,value in data.items(): # Here you will get key and value.
if value == '':
return JsonResponse({'error':1})
else:
pass

checking if json value is empty

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.

Check whether the JSON (object property exists) & print it as unicode decoded

You don't need the intricate tests on wether 'text' is present for the post caption.
This code works well with the JSON string you posted:

for post in data['data']:
if post.get('caption'):
print post['caption'].get('text', 0)

Furthermore, you could be more defensive and refer to data.get('data', []) when starting the loop in case Instagram sends you empty JSON.

How do I check if a string is valid JSON in Python?

You can try to do json.loads(), which will throw a ValueError if the string you pass can't be decoded as JSON.

In general, the "Pythonic" philosophy for this kind of situation is called EAFP, for Easier to Ask for Forgiveness than Permission.

check for null fields in json python

Define a set of values that should be replaced with None and use list comprehension to "replace" them:

>>> string_list = [ "foo",1,None, "null","[]","bar"]
>>> none_items = {"null", "[]"} # or set(("null", "[]"))
>>> [None if item in none_items else item for item in string_list]
['foo', 1, None, None, None, 'bar']

Or, use map():

>>> map(lambda x: None if x in none_items else x, string_list)
['foo', 1, None, None, None, 'bar']

Using set because of O(1) lookups.

check if JSON response has an object

print(email.get_list_of_emails()) return None. This is why you never get the break. Try to remove the print

Try to change the code to something like the below (it will give you better visibility)

while True:
data = email.get_list_of_emails()
if data is None:
print('data is None - going to sleep..')
time.sleep(5)
else:
print('we have data!')
print(data)
if ['id'] in data:
print('got it!')
break


Related Topics



Leave a reply



Submit