Reputation: 508
I am trying to see if a key and value pair exist in a JSON in python.
Here is what I have:
{
"cars": [
{
"model": "test"
},
{
"model": "test2"
}
]
}
I have tried this:
jsondata = open("test.json",'r').read()
fileData = json.loads(jsondata)
if "test" in [cars.model for cars in fileData]:
print('test')
Any help will be appreciated.
Upvotes: 1
Views: 1752
Reputation: 313
The best way i suggest would be to use dict and exception handling. Whenever a particular key is not found the 'KeyError' exception is raised, which would allow you to do the needful if the key does not exists.
In your case :
jsondata = open("test.json",'r').read()
fileData = json.loads(jsondata)
try:
cars = fileData['cars']
except KeyError:
print("Missing cars key")
Hope it helps!
Upvotes: 3
Reputation: 71580
Try this:
if "test" in [cars['model'] for cars in fileData['cars']]:
print('test')
Update:
print([cars for cars in fileData['cars'] if cars['model']=='test'])
Need to just do a list comprehension
Upvotes: 2