gpt4 book ai didi

python - 查找 json 中是否存在键值对

转载 作者:行者123 更新时间:2023-11-30 22:05:21 24 4
gpt4 key购买 nike

我正在尝试查看 python 中的 JSON 中是否存在键和值对。

这是我所拥有的:

{
"cars": [
{
"model": "test"
},
{
"model": "test2"
}
]
}

我已经尝试过这个:

jsondata = open("test.json",'r').read() 
fileData = json.loads(jsondata)

if "test" in [cars.model for cars in fileData]:
print('test')

任何帮助将不胜感激。

最佳答案

我建议的最好方法是使用字典和异常处理。每当未找到特定 key 时,都会显示“KeyError” ' 会引发异常,如果 key 不存在,这将允许您执行所需的操作。

就您而言:

jsondata = open("test.json",'r').read() 
fileData = json.loads(jsondata)

try:
cars = fileData['cars']
except KeyError:
print("Missing cars key")

希望对你有帮助!

关于python - 查找 json 中是否存在键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53038450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com