检查键/值是否在JSON中 [英] Check if key/value is in JSON
本文介绍了检查键/值是否在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:
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"
}
如何检查"body"是否为"present"(或"code"为"200")?我的脚本应该返回TRUE或FALSE
How can I check if 'body' is 'present' (or 'code' is '200')? My script should return TRUE or FALSE
更新
如果我按照答案中的建议添加此代码,则效果很好:
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)
推荐答案
您也应该检查一下body键是否确实存在.
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)
这篇关于检查键/值是否在JSON中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文