首页 > 解决方案 > TypeError 'bool' 对象不可下标

问题描述

我的代码是从 API 中提取 JSON 数据,但是我无法让我的代码从 JSON 对象中读取。

url = 'https://api.test.net/Vacancy'
payload = {
    "APIKey": "0000",
    "Action": "GetAllVacancies",
    "Content-Type" : "json",
}

headers = {}
r = requests.post(url, data=json.dumps(payload), headers=headers)
print(r.content)

cursor = mydb.cursor()

json_obj = r.json()
for index in json_obj:
            cursor.execute("INSERT INTO apidata (VacancyName, Department, Location) VALUES (%s, %s, %s)", (json_obj[index]["VacancyName"], (json_obj[index]["Department"], (json_obj[index]["Location"]))

cursor.close()

我的 JSON 响应如下所示

{ 
   "isError":false,
   "Status":0,
   "Message":"",
   "Result":[ 
      { 
         "VacancyName":"Test Vacancy",
         "VacancyDescription":"test data 123",
         "Location":"location 1",
         "Department":"Finance",

但是我不断收到错误

TypeError 'bool' 对象不可下标

我正在尝试提取此 JSON 数据并将其发送到数据库,谢谢!

标签: pythonjsonparsing

解决方案


您的 JSON 对象是一个dict. 遍历 dict 遍历键。

对象中的第一个键是"isError",所以当您尝试访问时,它json_obj[index]["Department"]等同于给出您所看到的错误。(json_obj["isError"]["Department"]False["Department"]

请在将来包括完整的错误消息,包括回溯。如果你这样做,回答这些问题会容易得多。


推荐阅读