检查键/值是否为JSON

时间:2015-02-28 10:13:07

标签: python json

使用此代码

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

我得到像这样的JSON-Feed:

{
 "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"
}

我如何检查'body'是否'存在'(或'代码'是'200')?我的脚本应该返回TRUE或FALSE

更新

如果我按照答案中的建议添加此代码,它可以正常工作:

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)

2 个答案:

答案 0 :(得分:5)

你也应该检查一下是否存在正文密钥。

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)

答案 1 :(得分: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"]))