Что-то не так с моим For l oop? - PullRequest
0 голосов
/ 16 апреля 2020

Я пытаюсь выполнить запрос GET к API, который возвращает JSON. Ответ JSON выглядит примерно так:

{
    "nodes": [
        {
            "id": "5C73B00598",
            "connectionState": "connected",
            "model": "PP152X"
        },
        {
            "id": "5C73B0059E",
            "connectionState": "connected",
            "model": "PP152X"
        },
        {
            "id": "4C72D012D8",
            "connectionState": "connected",
            "model": "PP203X"
        },
        {
            "id": "5C73B005DE",
            "connectionState": "connected",
            "model": "PP152X"
        },
        {
            "id": "5C73B005A2",
            "connectionState": "connected",
            "model": "PP152X"
        },
        {
            "id": "5C73B004A2",
            "connectionState": "disconnected",
            "model": "PP152X"
        },
        {
            "id": "5C73B0058B",
            "connectionState": "connected",
            "model": "PP152X"
        }
    ]
}

Упрощенная версия скрипта для возврата только одного ответа из одной папки API такова:

import requests
import json


url = "https://myurl.io/api/Customers/xxx/locations/xxx/nodes"

payload = {}
headers = {
  'Content-Type': 'application/x-www-form-urlencoded',
  'Authorization': 'xxx'
}

response = requests.request("GET", url, headers=headers, data = payload)
str = response.text.strip()



json_str = json.loads(str)
print(len(json_str['nodes']))
i = 0
while i <= len(json_str['nodes']):
    #cus_list = json_str['nodes'][i]['connectionState']
    #cus_lists.append(cus_list)
    print(json_str['nodes'][i]['connectionState'])
    i += 1

Когда я запустите этот скрипт, пока l oop не возвращает 7 итераций 'connectionState', а только первую.

Ответы [ 2 ]

2 голосов
/ 16 апреля 2020

Попробуйте:

for i in json_str['nodes']:
    print(i['connectionState'])

Это дает:

connected
connected
connected
connected
connected
disconnected
connected
0 голосов
/ 16 апреля 2020

я всегда должен быть меньше чем len ()

json_str = json.loads(str)
print(len(json_str['nodes']))
i = 0
while i < len(json_str['nodes']):
    #cus_list = json_str['nodes'][i]['connectionState']
    #cus_lists.append(cus_list)
    print(json_str['nodes'][i]['connectionState'])
    i += 1
...