2017-10-04 53 views
0

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

如何检查blackListCountry是否存在于其中?

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

[最有效的方法可能的重复检查,如果字典项存在,并且如果处理其价值它确实](https://stackoverflow.com/questions/28859095/most-efficient-method-to-check-if-dictionary-key-exists-and-process-its-value-if) – coder

+0

“json”是一个文本格式,而不是数据类型。你在这里有一个简单的'dict'。 –

回答

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

最简单的方法来做到这一点:

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

in搜索键 'blackListCountry',并返回布尔真或假。

1

request.json()实际上将返回一个字典,所以你可以使用.get()方法,如果关键是没有找到它返回None

blackListCountry = request.json.get("blackListCountry") 

if blackListCountry is None: 
    # key is not found 
else: 
    print(blackListCountry) 
相关问题