python - 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 数据并将其发送到数据库,谢谢!
解决方案
您的 JSON 对象是一个dict
. 遍历 dict 遍历键。
对象中的第一个键是"isError"
,所以当您尝试访问时,它json_obj[index]["Department"]
等同于给出您所看到的错误。(json_obj["isError"]["Department"]
False["Department"]
请在将来包括完整的错误消息,包括回溯。如果你这样做,回答这些问题会容易得多。
推荐阅读
- python - 在 Numpy 中为 3D 数组添加新行
- laravel - 在模型中从 belongsTo() 关系获取特定属性而不附加整个集合
- ionic-framework - 如何在 Ionic 6 上检查离子无线电时更改离子标签颜色?
- reactjs - Ant Design 菜单和菜单项自定义
- python - 获取 Pyrebase HTTPError 信息
- javascript - D3js增加X轴之间的空间
- html - 在 HTML 电子邮件中显示图像
- javascript - 如何使用已转译的 gulp "main.js"
- c++ - VC++ 中更安全的字符串复制功能,但如何处理 TCHAR*?
- c - C Lang:使用指针和数组检查是否回文