如何检查JSON是否指定了数据?

时间:2017-10-04 11:18:56

标签: python json dictionary

我需要检查JSON请求是否有指定的字段。我的要求可以是: {"ip": "8.35.60.229", "blackListCountry" : "Az"}或简单地:{"ip": "8.35.60.229"}

如何检查其中是否存在blackListCountry

userIP = request.json["ip"]
blackListCountry = request.json["blackListCountry"]
print(blackListCountry)

3 个答案:

答案 0 :(得分:1)

最简单的方法:

x = {"ip": "8.35.60.229", "blackListCountry" : "Az"}
print('blackListCountry' in x)
> True

in搜索键' blackListCountry'并返回bool判断对错。

答案 1 :(得分:1)

request.json()实际上会返回一个字典,因此如果找不到密钥,您可以使用返回.get()的{​​{1}}方法:

None

答案 2 :(得分:0)

x = {"ip": "8.35.60.229", "blackListCountry" : "Az"}
if "blackListCountry" in x:
    #key exists
else:
    #key doesn't exists