gpt4 book ai didi

python - 在 Python 中循环遍历 JSON 数组

转载 作者:太空狗 更新时间:2023-10-30 00:27:29 29 4
gpt4 key购买 nike

我从 API 中获取了以下数据。我正在尝试使用 Python 脚本访问餐厅名称并让脚本显示它。这是我的文件:

测试.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"
},

目前,它会显示第一个餐厅名称 3 次。我希望它遍历每个 restaurant 对象并显示键“name”的值。任何帮助,将不胜感激。

最佳答案

restaurants 是您的列表时,您必须迭代此键:

for restaurant in data['restaurants']:
print restaurant['restaurant']['name']

关于python - 在 Python 中循环遍历 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42445237/

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