Python 检查键/值是否在 JSON 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28780547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:45:15  来源:igfitidea点击:

Check if key/value is in JSON

pythonjson

提问by Simon

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:

我得到一个这样的 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"
}

How can I check if 'body' is 'present' (or 'code' is '200')? My script should return TRUE or FALSE

如何检查“body”是否“存在”(或“code”是否为“200”)?我的脚本应该返回 TRUE 或 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)

采纳答案by Alexandru Godri

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)

回答by Padraic Cunningham

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"]))