Check both, the key existence and its length:
import json, sys
obj=json.load(sys.stdin)
if not 'results' in obj or len(obj['results']) == 0:
exit(0)
else:
exit(1)
Answer from Thiago Rossener on Stack OverflowCheck both, the key existence and its length:
import json, sys
obj=json.load(sys.stdin)
if not 'results' in obj or len(obj['results']) == 0:
exit(0)
else:
exit(1)
import json, sys
obj=json.load(sys.stdin)
if len(obj["results"])==0:
exit(0)
else:
exit(1)
try using the length of obj["results"]
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'):
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:
Let's say I have a JSON object like this:
{"Data":[{"key1":"value1"},{"key2":"value2"},
{}]
}
If I wanted a list to look as follows: ['value1', 'value2', '']. How would I go about pulling in that null JSON key/value? Is that possible?
Thank you!
"example" in data.keys() will return True or False, so this would be one way to check.
So, given JSON like this...
{ "example": { "title": "example title"}}
And given code to load the file like this...
import json
with open('example.json') as f:
data = json.load(f)
The following code would return True or False:
x = "example" in data # x set to True
y = "cheese" in data # y set to False
You can try:
if data.get("example") == "":
...
This will not raise an error, even if the key "example" doesn't exist.
What is happening in your case is that data["example"] does not equal "", and in fact there is no key "example" so you are probably seeing a KeyError which is what happens when you try to access a value in a dict using a key that does not exist. When you use .get("somekey"), if the key "somekey" does not exist, get() will return None and will return the value otherwise. This is important to note because if you do a check like:
if not data.get("example"):
...
this will pass the if test if data["example"] is "" or if the key "example" does not exist.
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.
Basically when json loads and deserializes your object, null in JSON will become None in python.
So your line of:
if post['caption'] is not 'null':
Should become:
if post['caption']:
You can use any(), returning True if any of the values in the JSON object are truthy:
Copydata = {
'a': [],
'b': [],
'c': [1,2,3]
}
result = any(item for item in data.values())
print(result)
This outputs:
CopyTrue
Empty lists are Falsy so you can check for the Truthness of value against each key. e.g.,
Copy>>> a = json.loads('{"a" : [], "b" : [], "c" : [1,2,3]}')
>>> for i,j in a.items():
... if j:
... print(j)
...
[1, 2, 3]