首页 > 解决方案 > 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
    }
}

标签: pythonjson

解决方案


您没有将文本转换为 json。尝试

data = json.loads(res.text)

或者

data = res.json()

除此之外,您可能需要更改 for 循环以循环遍历值而不是键。将其更改为以下内容

for recipe in data['recipes'].values()

推荐阅读