0

当我要查找的内容有多个“节点”时,我能够解析 json 响应,但是当 API 仅返回一个节点时,我收到消息“字符串索引必须是整数”。这是我的代码,在使用 json.loads() 将其从字符串转换后传入字典:

import requests, requests.auth
import json
import os

def parseSchedule(dict):
    i = 0
    for item in dict['reservations']['reservation']:
        print(item['event_start_dt'])
        i += 1

我已经简化了 json 响应以表明它有效:

    {
    "reservations": {
        "reservation": [{
            "event_start_dt": "2019-11-27T12:40:00-08:00"
        }, {
            "event_start_dt": "2019-11-27T16:10:00-08:00"
        }]
    }
}

虽然这会引发错误“字符串索引必须是整数”:

    {
    "reservations": {
        "reservation": {
            "event_start_dt": "2019-11-26T08:30:00-08:00"   
        }
    }
}

我研究了 .items() ,我在其中尝试了键和值,但到目前为止还没有成功。

4

1 回答 1

0

你可以这样做:

#If it is a list:
if str(type(dict["reservations"]["reservation"])) == "<class 'list'>":
    for i in range(len(dict["reservations"]["reservation"])):
        print(dict["reservations"]["reservation"][i]["event_start_dt"])
else: #If it is not a list
    print(dict['reservations']['reservation']['event_start_dt'])
于 2019-11-30T22:19:11.533 回答