Check if key / value is in JSON

Using 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 JSON-Feed as follows:

 { "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 to check if 'body' is 'present' (or 'code' is '200')? My script should return TRUE or FALSE

UPDATE

If I add this code as suggested 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) 
+5
source share
2 answers

You can also check if there really is a body key.

 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) 
+5
source
 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"])) 
+3
source

Source: https://habr.com/ru/post/1214374/


All Articles