2017-10-04 27 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) 
相關問題