Check if key/value is in JSON
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2
--
Chapters
00:00 Question
01:08 Accepted answer (Score 7)
01:29 Answer 2 (Score 3)
01:42 Thank you
--
Full question
https://stackoverflow.com/questions/2878...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #json
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2
--
Chapters
00:00 Question
01:08 Accepted answer (Score 7)
01:29 Answer 2 (Score 3)
01:42 Thank you
--
Full question
https://stackoverflow.com/questions/2878...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #json
#avk47
ACCEPTED ANSWER
Score 7
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)
ANSWER 2
Score 3
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"]))