我从API获取以下数据。我试图使用Python脚本访问餐厅名称并让脚本显示它。这是我的文件:
test.py
with open('data.json') as data_file:
data = json.load(data_file)
for restaurant in data:
print data ['restaurants'][0]['restaurant']['name']
我的JSON文件如下:(简化)
{
"results_found": 3296,
"results_start": 0,
"results_shown": 20,
"restaurants": [
{
"restaurant": {
"R": {
"res_id": 9101083
},
"id": "9101083",
"name": "My Meat Wagon",
"address": "Market Square, Smithfield, Dublin Dublin 7",
"locality": "Smithfield",
"city": "Dublin",
"city_id": 91,
"latitude": "53.3489980000",
"longitude": "-6.2788120000",
"zipcode": "Dublin 7",
"events_url": "https://www.zomato.com/dublin/my-meat-wagon-smithfield/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"establishment_types": []
}
},
{
"restaurant": {
"R": {
"res_id": 9101628
},
"id": "9101628",
"name": "Wowburger",
"url": "https://www.zomato.com/dublin/wowburger-temple-bar?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"location": {
"address": "The Workmans Club, 11 Wellington Quay, Temple Bar, Dublin Dublin 2",
"locality": "The Workmans Club",
"city": "Dublin",
"city_id": 91,
"latitude": "53.3452863158",
"longitude": "-6.2663815543",
"zipcode": "Dublin 2",
"country_id": 97,
"locality_verbose": "The Workmans Club, Dublin"
},
"switch_to_order_menu": 0,
"cuisines": "Burger",
"average_cost_for_two": 20,
"establishment_types": []
}
},
{
"restaurant": {
"R": {
"res_id": 16520426
},
"id": "16520426",
"name": "Brother Hubbard",
"locality_verbose": "North City, Dublin"
},
目前,它会三次显示第一个餐馆名称。我希望它循环遍历每个restaurant
对象,并显示键" name"的值。任何帮助,将不胜感激。
答案 0 :(得分:8)
当restaurants
是您的列表时,您必须迭代此键:
for restaurant in data['restaurants']:
print restaurant['restaurant']['name']
答案 1 :(得分:0)
with open('data.json') as data_file:
data = json.load(data_file)
for restaurant in data['restaurant']:
print restaurant['restaurant']['name']
这样,您将遍历“餐馆”字段内的词典列表中的元素并输出其名称。
你真的很亲密,你之前做的是循环json文件中的所有主要字段并每次打印第一家餐馆的名称(data['restaurants'][0]
为您提供餐馆列表中的第一家餐厅......而且你每次都打印它的名字