【问题标题】:Is there something wrong with my For loop?我的 For 循环有问题吗?
【发布时间】:2020-04-16 10:13:18
【问题描述】:

我正在尝试对返回 JSON 的 API 运行 GET 请求。 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

当我运行这个脚本时,while 循环不会返回 'connectionState' 的 7 次迭代,而只是返回第一次。

【问题讨论】:

  • 不回答您的问题,但您的 while 循环中的条件应使用 &lt;。还要粘贴该打印语句的实际输出和响应,而不是输出的截断版本。
  • 抛开条件,循环似乎很好。您确定它从 api 响应返回 7 而不是 1?

标签: python json loops python-requests


【解决方案1】:

试试:

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

这给出了:

connected
connected
connected
connected
connected
disconnected
connected

【讨论】:

    【解决方案2】:

    i 必须始终小于 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-23
      • 2021-10-25
      • 2016-05-05
      • 1970-01-01
      • 1970-01-01
      • 2011-08-17
      相关资源
      最近更新 更多