Nicholas Bartlett
Nicholas Bartlett

Reputation: 53

Is there something wrong with my For loop?

I am trying to run a GET request to an API that returns JSON. The JSON response looks something like this:

{
    "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"
        }
    ]
}

The simplified version of the script to just return one response from one API folder is this so far:

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

When I run this script the while loop does not return 7 iterations of the 'connectionState' but rather just the first one.

Upvotes: 0

Views: 70

Answers (2)

Mace
Mace

Reputation: 1410

i must always be smaller then the 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

Upvotes: 0

Joshua Varghese
Joshua Varghese

Reputation: 5202

Try:

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

This gives:

connected
connected
connected
connected
connected
disconnected
connected

Upvotes: 2

Related Questions