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

标签 python json

我从 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/

相关文章:

python - 为什么django不能同时加载多个页面?

python regexp方法返回一个包含空元素的列表

json - 设置 Azure ARM 模板服务器场的 sku 名称和层

java - 当用户单击微调器中的一项时,它应该显示另一项数据将从 JSON Web 服务获取

python - 当我使用 json.loads 时,你是什么?

python - 对 Python 3 中 while 循环的输出进行排序

Python KMax 池化 (MXNet)

python - 向数据框添加值并导出

java - JSON/Java/Twilio 响应 : "No ' To' number is specified"when request sent from JSON

python - 将具有重复键的嵌套 JSON 文件转换为 Python 中的数据框