在Python中循环遍历JSON数组 [英] Looping through a JSON array in Python

查看:8849
本文介绍了在Python中循环遍历JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following data taken from an API. I am trying to access the restaurant name using a Python script and have the script display it. Here are my files:

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文件如下:(简体)

my JSON file is as follows: (simplified)

    {
  "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对象并显示键名称"的值.任何帮助,将不胜感激.

Currently, it displays the first restaurant name three times. I want it to loop through each restaurant object and display the value for the key "name". Any help would be appreciated.

推荐答案

restaurants是您的列表时,您必须遍历此键:

When restaurants is your list, you have to iterate over this key:

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

这篇关于在Python中循环遍历JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆