python - python TypeError:字符串索引必须是整数json
问题描述
有人能告诉我我做错了什么吗?我遇到了这个错误..经历了类似错误的早期帖子。无法理解。。
import json
import re
import requests
import subprocess
res = requests.get('https://api.tempura1.com/api/1.0/recipes', auth=('12345','123'), headers={'App-Key': 'some key'})
data = res.text
extracted_recipes = []
for recipe in data['recipes']:
extracted_recipes.append({
'name': recipe['name'],
'status': recipe['status']
})
print extracted_recipes
TypeError:字符串索引必须是整数
数据包含以下
{
"recipes": {
"47635": {
"name": "Desitnation Search",
"status": "SUCCESSFUL",
"kitchen": "eu",
"active": "YES",
"created_at": 1501672231,
"interval": 5,
"use_legacy_notifications": false
},
"65568": {
"name": "Validation",
"status": "SUCCESSFUL",
"kitchen": "us-west",
"active": "YES",
"created_at": 1522583593,
"interval": 5,
"use_legacy_notifications": false
},
"47437": {
"name": "Gateday",
"status": "SUCCESSFUL",
"kitchen": "us-west",
"active": "YES",
"created_at": 1501411588,
"interval": 10,
"use_legacy_notifications": false
}
},
"counts": {
"total": 3,
"limited": 3,
"filtered": 3
}
}
解决方案
您没有将文本转换为 json。尝试
data = json.loads(res.text)
或者
data = res.json()
除此之外,您可能需要更改 for 循环以循环遍历值而不是键。将其更改为以下内容
for recipe in data['recipes'].values()
推荐阅读
- asp.net-core-2.0 - 必须声明表变量“@p0”
- c# - 没有父属性的二叉搜索树迭代器c#
- python - cv2.waitKey(25) & 0xFF == ord('q'): 和 cv2.imwrite() 不工作
- jquery - 如何在 django 视图中反序列化来自 jquery/ajax 的数据
- apache-spark - 纱线模式下的火花历史服务器
- git - Git:直接在工作目录中进行的更改(链接到裸存储库)
- css - 有没有比 modal-lg 提供更大宽度的类?
- macos - 如何在不进行迁移的情况下卸载 macports?
- javascript - 使用 Ajax 显示部分视图模型 - ASP.NET C# AJAX JQuery
- html - 我怎样才能使这些盒子的尺寸相同?