How to Find a Specific Field Value from a JSON list in Python
To find a specific field value from a JSON list in Python, you can iterate through the list of JSON objects and access the desired field in each object.
Here's an example of finding the price of a laptop with the name "samsung" in the list, and then printing it:
json_list = [
{
"laptop_name": "dell",
"price": 500
},
{
"laptop_name": "acer",
"price": 400
},
{
"laptop_name": "samsung",
"price": 600
}
]
def find_price_from_json_list(json_list, laptop_name):
for dict in json_list:
if dict['laptop_name'] == laptop_name:
return dict['price']
#Calling method
price = find_price_from_json_list(json_list,'samsung')
print(price)
The output of the above code is as follows:
600
Using Python List comprehension to get the price of a specific laptop name:
json_list = [
{
"laptop_name": "dell",
"price": 500
},
{
"laptop_name": "acer",
"price": 400
},
{
"laptop_name": "samsung",
"price": 600
}
]
def find_price(json_list, laptop_name):
return [p for p in json_list if p['laptop_name']==laptop_name][0]['price']
#Calling method
price = find_price(json_list,"samsung")
print(price)
Output:
600