What about using if/else?
mastercounter = 0
phdcounter = 0
nodeegreecounter = 0
for candidate in response["person"]:
if item["Degree"]:
if item["Degree"]["key"] == "Master":
mastercounter = mastercounter + 1
if item["license"]["key"] == "PhD":
phdcounter = phdcounter + 1
else:
nodegreecounter = nodegreecounter + 1
Answer from tkrishtop on Stack OverflowWhat about using if/else?
mastercounter = 0
phdcounter = 0
nodeegreecounter = 0
for candidate in response["person"]:
if item["Degree"]:
if item["Degree"]["key"] == "Master":
mastercounter = mastercounter + 1
if item["license"]["key"] == "PhD":
phdcounter = phdcounter + 1
else:
nodegreecounter = nodegreecounter + 1
It depends on how your JSON is organized. I suspect the response is a sequence of persons. Like this:
response = [{"id": "1", "Degree": "Master"}, {"id": "2", "Degree": null}]
Therefore you should use:
for person in response:
you only need one attribute of a person (named "Degree").
Thus, if a person is a sequence of attributes, the code becomes:
for person in response:
if person["Degree"] is None:
nodegreecounter = nodegreecounter + 1
elif person["Degree"] == "Master":
mastercounter = mastercounter + 1
elif person["Degree"] == "PhD":
phdcounter = phdcounter + 1
If your JSON is organized differently, you should explain the JSON structure before asking for advice.
If your JSON looks like this:
{"key11": {"id": "1", "Degree": "Master"}, "key12": {"id": "2", "Degree": null}}
The code can be:
for key in response:
if response[key]["Degree"] is None:
nodegreecounter = nodegreecounter + 1
elif response[key]["Degree"] == "Master":
mastercounter = mastercounter + 1
elif response[key]["Degree"] == "PhD":
phdcounter = phdcounter + 1
or
for key, person in response.items():
if person["Degree"] is None:
nodegreecounter = nodegreecounter + 1
elif person["Degree"] == "Master":
mastercounter = mastercounter + 1
elif person["Degree"] == "PhD":
phdcounter = phdcounter + 1
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']:
How to parse completely empty JSON key/values?
python - Checking if JSON key is empty - Stack Overflow
Conditional statement to check if a JSON key is null with Python 3 - Stack Overflow
Check if key exists and iterate the JSON array using Python - Stack Overflow
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!
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)
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"]
import json
jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"}"""
def getTargetIds(jsonData):
data = json.loads(jsonData)
if 'to' not in data:
raise ValueError("No target in given data")
if 'data' not in data['to']:
raise ValueError("No data for target")
for dest in data['to']['data']:
if 'id' not in dest:
continue
targetId = dest['id']
print("to_id:", targetId)
Output:
In [9]: getTargetIds(s)
to_id: 1543
If all you want is to check if key exists or not
h = {'a': 1}
'b' in h # returns False
If you want to check if there is a value for key
h.get('b') # returns None
Return a default value if actual value is missing
h.get('b', 'Default value')
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.
You could try:
string_list = [ "foo",1,None, "null","[]","bar"]
nones = [ "null", "[]" ]
print([None if s in nones else s for s in string_list])
Ok... This is a little complicated... So... Sorry in advance
I have a function that returns attributes of a video file (FFprobe) in a JSON object, and then a little factory that parses the JSON looking for specific attributes, and running if statements on those attributes.
I.E. One of attributes in the JSON is subtitle format. So if the subtitle format != a desired format, then set a variable that is used in another format for encoding the subtitle to the desired format
The issue that I have run into so that sometimes those attributes (like subtitle) don't exist in the JSON because they do not exist in the file.
So I sort of need to check if the attribute in the JSON exists, before I check to see if if that attribute is the desired attribute and start setting variables
How do I do this?
Would it be as simple as:
json_object= json.loads(studentJson)
if "subtitle_format" in json_object:
print("Key exist in json_object")
print(subtitle_format["ASS"], " is the subtitle format")
else:
print("Key doesn't exist in JSON data")If yes, would I get yelled at if the if statement had a few layers? Psudo:
if subtitle_format in json_object:
if subtitle_format == ass
if subtitle_format == english
encode
"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 should also maybe check if the body key is actually there.
def checkJson(jsonContents):
bodyFlag = True if "body" in jsonContents["objects"][0]["data"] and jsonContents["objects"][0]["data"]["body"] == "Present" else False
codeFlag = True if "code" in jsonContents["objects"][0]["data"] and jsonContents["objects"][0]["data"]["code"] == 200 else False
return bodyFlag or codeFlag
print checkJson(result)
d = json.loads(results)
objs = d["objects"][0]
# see if any code is either == 200 or "body" is a key in the subdict
return any(x for x in (objs["data"]["code"] == 200,"body" in objs["data"]))
The preferred way, when applicable:
for r in results:
print r.get('key_name')
this will simply print None if key_name is not a key in the dictionary. You can also have a different default value, just pass it as the second argument:
for r in results:
print r.get('key_name', 'Missing: key_name')
If you want to do something different than using a default value (say, skip the printing completely when the key is absent), then you need a bit more structure, i.e., either:
for r in results:
if 'key_name' in r:
print r['key_name']
or
for r in results:
try: print r['key_name']
except KeyError: pass
the second one can be faster (if it's reasonably rare than a key is missing), but the first one appears to be more natural for many people.
There are two straightforward ways of reading from Python dict if key might not be present. for example:
dicty = {'A': 'hello', 'B': 'world'}
- The pythonic way to access a key-value pair is:
value = dicty.get('C', 'default value')
- The non-pythonic way:
value = dicty['C'] if dicty['C'] else 'default value'
- even worse:
try:
value = dicty['C']
except KeyError as ke:
value = 'default value'
You should use the built-in json module, which was designed explicitly for this task:
>>> import json
>>> data = '''
... {
... "abc": null,
... "def": 9
... }
... '''
>>> json.loads(data)
{'def': 9, 'abc': None}
>>> type(json.loads(data))
<class 'dict'>
>>>
By the way, you should use this method even if your JSON data contains no null values. While it may work (sometimes), ast.literal_eval was designed to evaluate Python code that is represented as a string. It is simply the wrong tool to work with JSON data.
One solution is to use a variable that contains None.
import json
null = None
data = { "test": null }
json.dumps(data)