Hướng dẫn loop json python - con trăn vòng lặp json

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']

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"
        },

Currently, it displays the first restaurant name three times. I want it to loop through each

{ 
    string: value, string: value,..............
}
3 object and display the value for the key "name". Any help would be appreciated.

Nếu bạn có chuỗi JSON, bạn có thể phân tích nó bằng cách sử dụng phương thức JSON.LOADS ().Kết quả sẽ là một từ điển Python.using the json.loads() method. The result will be a Python dictionary.

Trong đó, File_Name là tên của tệp JSON trong đó, dữ liệu JSON được lưu trữ.

Chương trình nghị sự

  • Giới thiệu
  • Lặp lại đối tượng JSON bằng phương thức tải () với vòng lặp
  • Lặp lại tệp json bằng tải () và cho vòng lặp
  • Bản tóm tắt

Giới thiệu

Lặp lại đối tượng JSON bằng phương thức tải () với vòng lặp

Lặp lại tệp json bằng tải () và cho vòng lặp

{ 
    string: value, string: value,..............
}

Bản tóm tắt

JSON là viết tắt của ký hiệu đối tượng JavaScript. Sử dụng JSON, chúng ta có thể lưu trữ dữ liệu ở định dạng cặp giá trị khóa. Ưu điểm chính của JSON là chúng ta có thể dễ dàng hiểu dữ liệu.

Lặp lại đối tượng JSON bằng phương thức tải () với vòng lặp

Lặp lại tệp json bằng tải () và cho vòng lặp

  • Bản tóm tắt

Syntax:

loaded = json.loads(input_json_string)

JSON là viết tắt của ký hiệu đối tượng JavaScript. Sử dụng JSON, chúng ta có thể lưu trữ dữ liệu ở định dạng cặp giá trị khóa. Ưu điểm chính của JSON là chúng ta có thể dễ dàng hiểu dữ liệu.input_json_string is the JSON string or object

  • Cấu trúc JSON:

Syntax:

for iterator in loaded:
    print(iterator, ":", loaded[iterator])

Hãy cùng xem các cách để lặp lại một đối tượng JSON.iterator is used to iterate the keys in a dictionary. Let’s see the example, to understand it better.

Quảng cáo

# import JSON module
import json

# Consider the json string with 5 values
input_json_string = '{  "tutorial-1": "python", \
                        "tutorial-2": "c++",    \
                        "tutorial-3": "pandas", \
                        "tutorial-4": "numpy",  \
                        "tutorial-5": ".net"}'

# Load input_json_string into a dictionary-loaded
loaded = json.loads(input_json_string)

# Loop along dictionary keys
for iterator in loaded:
    print(iterator, ":", loaded[iterator])

Output:

tutorial-1 : python
tutorial-2 : c++
tutorial-3 : pandas
tutorial-4 : numpy
tutorial-5 : .net

Trong kịch bản này,

Chúng tôi sẽ tạo một chuỗi JSON và tải nó vào một từ điển bằng phương thức Loads ().

trong đó input_json_string là chuỗi hoặc đối tượng JSONinput_json_string is the JSON string or object

import json

# Consider the json string with 5 key value pairs, where each value is a list
input_json_string = '{  "tutorial-1": ["subject1","subject2","subject3"],  \
                        "tutorial-2":  ["subject1","subject2","subject3"], \
                        "tutorial-3":  ["subject1","subject2","subject3"], \
                        "tutorial-4":  ["subject1","subject2","subject3"], \
                        "tutorial-5":  ["subject1","subject2","subject3"] }'

# Load input_json_string into a dictionary-loaded
loaded = json.loads(input_json_string)

# Loop along dictionary keys
for iterator in loaded:
    print(iterator, ":", loaded[iterator])

Output:

tutorial-1 : ['subject1', 'subject2', 'subject3']
tutorial-2 : ['subject1', 'subject2', 'subject3']
tutorial-3 : ['subject1', 'subject2', 'subject3']
tutorial-4 : ['subject1', 'subject2', 'subject3']
tutorial-5 : ['subject1', 'subject2', 'subject3']

Lặp lại từ điển đó (được tải) bằng cách sử dụng vòng lặp với trình lặp.

trong đó người lặp được sử dụng để lặp lại các phím trong từ điển. Hãy cùng xem ví dụ, để hiểu nó tốt hơn.iterator is used to iterate the keys in a dictionary. Let’s see the example, to understand it better.

Trong ví dụ này, chúng tôi đã tạo một chuỗi JSON với 5 phần tử và lặp lại sử dụng cho Loop.

import json

# consider the json string with 2 string elements
# with 3 key-value pairs through a dictionary
input_json_string = '{"tutorial-1": {"subject1":"python",   \
                                     "subject2":"php",      \
                                     "subject3":"node.js"}, \
                      "tutorial-2": {"subject1":"java",     \
                                     "subject2":"android",  \
                                      "subject3":"css" } }'

# Load input_json_string into a dictionary-loaded
loaded = json.loads(input_json_string)

#Loop along dictionary keys
for iterator in loaded:
    print(iterator, ":", loaded[iterator])

Output:

    {
  "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"
        },
00

Lặp lại tệp json bằng tải () và cho vòng lặp

Bản tóm tắt

JSON là viết tắt của ký hiệu đối tượng JavaScript. Sử dụng JSON, chúng ta có thể lưu trữ dữ liệu ở định dạng cặp giá trị khóa. Ưu điểm chính của JSON là chúng ta có thể dễ dàng hiểu dữ liệu. Open the file.

Cấu trúc JSON:

Syntax:

    {
  "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"
        },
01

Trong đó, File_Name là tên của tệp JSON trong đó, dữ liệu JSON được lưu trữ.

Hãy cùng xem các cách để lặp lại một đối tượng JSON. Load the json string into a variable

Quảng cáo

Trong kịch bản này, Iterate that dictionary using for loop with an iterator.

Chúng tôi sẽ tạo một chuỗi JSON và tải nó vào một từ điển bằng phương thức Loads ().

for iterator in loaded:
    print(iterator, ":", loaded[iterator])

trong đó input_json_string là chuỗi hoặc đối tượng JSONinput_json_string is the JSON string or object

Lặp lại từ điển đó (được tải) bằng cách sử dụng vòng lặp với trình lặp.

trong đó người lặp được sử dụng để lặp lại các phím trong từ điển. Hãy cùng xem ví dụ, để hiểu nó tốt hơn.iterator is used to iterate the keys in a dictionary. Let’s see the example, to understand it better.

    {
  "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"
        },
04

Trong ví dụ này, chúng tôi đã tạo một chuỗi JSON với 5 phần tử và lặp lại sử dụng cho Loop.

Từ đầu ra, chúng ta có thể thấy rằng tất cả các giá trị có trong JSON được lặp lại.

Output:

tutorial-1 : python
tutorial-2 : c++
tutorial-3 : pandas
tutorial-4 : numpy
tutorial-5 : .net

Ví dụ 2:

Chúng tôi sẽ tạo một chuỗi JSON và tải nó vào một từ điển bằng phương thức Loads ().

trong đó input_json_string là chuỗi hoặc đối tượng JSONinput_json_string is the JSON string or object

Lặp lại từ điển đó (được tải) bằng cách sử dụng vòng lặp với trình lặp.

    {
  "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"
        },
07

Trong ví dụ này, chúng tôi đã tạo một chuỗi JSON với 5 phần tử và lặp lại sử dụng cho Loop.

    {
  "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"
        },
08

Output:

tutorial-1 : ['subject1', 'subject2', 'subject3']
tutorial-2 : ['subject1', 'subject2', 'subject3']
tutorial-3 : ['subject1', 'subject2', 'subject3']
tutorial-4 : ['subject1', 'subject2', 'subject3']
tutorial-5 : ['subject1', 'subject2', 'subject3']

Ví dụ 2:

Nếu có nhiều giá trị được gắn vào một phần tử chuỗi, phương thức tải () hoạt động tốt. Hãy cùng xem cách lặp lại tất cả các giá trị trong một danh sách. In this example, we will consider the json string with 2 string elements and with 3 key-value pairs in each of them. We will load it in a dictionary and iterate using for loop.

Lặp lại từ điển đó (được tải) bằng cách sử dụng vòng lặp với trình lặp.

{ 
    string: value, string: value,..............
}
0

Trong ví dụ này, chúng tôi đã tạo một chuỗi JSON với 5 phần tử và lặp lại sử dụng cho Loop.

{ 
    string: value, string: value,..............
}
1

Output:

    {
  "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"
        },
00

Ví dụ 2:

Bản tóm tắt

JSON là viết tắt của ký hiệu đối tượng JavaScript. Sử dụng JSON, chúng ta có thể lưu trữ dữ liệu ở định dạng cặp giá trị khóa. Ưu điểm chính của JSON là chúng ta có thể dễ dàng hiểu dữ liệu.

Nếu bạn có chuỗi JSON, bạn có thể phân tích nó bằng cách sử dụng phương thức JSON.LOADS ().Kết quả sẽ là một từ điển Python.using the json.loads() method. The result will be a Python dictionary.using the json.loads() method. The result will be a Python dictionary.

"Làm thế nào để tôi lặp lại một cấu trúc JSON?"Bạn không.Bạn phân tích nó, trong đó bạn không còn JSON nữa, và bạn lặp qua mảng kết quả.You don't. You parse it, whereupon you don't have JSON anymore, and you loop through the resulting array.You don't. You parse it, whereupon you don't have JSON anymore, and you loop through the resulting array.

Ngoài JSON, hàm Open () gốc của Python cũng sẽ được yêu cầu.Thay vì phương thức tải JSON, đọc các chuỗi JSON, phương thức được sử dụng để đọc dữ liệu JSON trong tệp là load ().Phương thức Load () chiếm một đối tượng tệp và trả về dữ liệu JSON được phân tích cú pháp vào một đối tượng Python.load(). The load() method takes up a file object and returns the JSON data parsed into a Python object.load(). The load() method takes up a file object and returns the JSON data parsed into a Python object.

Bạn cần chuyển đổi chuỗi của một đối tượng JSON thành Python dict trước khi bạn có thể truy cập nó.Lưu câu trả lời này.Hiển thị hoạt động trên bài viết này.Thông thường JSON sẽ là một chuỗi và bạn sẽ thử và bỏ nó vào biểu đồ đối tượng (trong Python thường được tạo thành từ bản đồ và mảng).convert the string of a json object to python dict before you can access it. Save this answer. Show activity on this post. Usually the json will be a string and you will try and deserialise it into a object graph (which in python are typically are made up of maps and arrays).convert the string of a json object to python dict before you can access it. Save this answer. Show activity on this post. Usually the json will be a string and you will try and deserialise it into a object graph (which in python are typically are made up of maps and arrays).