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

2024-09-30 10:30:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要检查JSON请求是否指定了字段。我的请求可以是: {"ip": "8.35.60.229", "blackListCountry" : "Az"}或者干脆:{"ip": "8.35.60.229"}。你知道吗

如何检查其中是否存在blackListCountry?你知道吗

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

Tags: ipjsonrequestazprintuseripblacklistcountry
3条回答

request.json()实际返回dict,因此可以使用.get()方法,如果找不到键,则返回None

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

if blackListCountry is None:
    # key is not found
else:
    print(blackListCountry)

最简单的方法:

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

in搜索“blackListCountry”键并返回bool True或False。你知道吗

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

相关问题 更多 >

    热门问题