Check if key/value is in JSON

json, python

Solution

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)

Problem

With this code ``` import sense import json sense.api_key = '...' node = sense.Node.retrieve('........') feed = node.feeds.retrieve('presence') events = feed.events.list(limit=1) result = json.dumps(events,indent=1) print result ``` I get a JSON-Feed like this: ``` { "links": {...}, "objects": [ { "profile": "GenStandard", "feedUid": ".....", "gatewayNodeUid": ".....", "dateServer": "2015-02-28T09:57:22.337034", "geometry": null, "data": { "body": "Present", "code": 200 }, "signal": "-62", "dateEvent": "2015-02-28T09:57:22.000000", "type": "presence", "payload": "2", "nodeUid": "....." } ], "totalObjects": 875, "object": "list" } ``` How can I check if 'body' is 'present' (or 'code' is '200')? My script should return TRUE or FALSE UPDATE If I add this code as proposed in the answers it works fine: ``` d=json.loads(result) def checkJson(jsonContents): bodyFlag = True if "body" in jsonContents["objects"][0]["data"] and jsonContents["objects"][0]["data"]["body"] == "Present" else False return bodyFlag print checkJson(d) ```

Original source