0

I need to check if JSON request have specified field. My request can be: {"ip": "8.35.60.229", "blackListCountry" : "Az"} or simply: {"ip": "8.35.60.229"}.

How to check if blackListCountry is exists in it?

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

3 Answers 3

2

request.json() actually return a dict, so you can use the .get() method which returns None if key is not found:

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

if blackListCountry is None:
    # key is not found
else:
    print(blackListCountry)
Sign up to request clarification or add additional context in comments.

Comments

1

The simplest way to do this:

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

in search key 'blackListCountry' and return bool True or False.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.