如何使用 python(django) 从 mashape 访问字典列表?

How to access list of dictionaries from mashape using python(django)?

我正在发送一个 URL 作为请求,作为响应,我得到了一个字典列表,但我无法循环遍历这些值。

def profile_model(request):
    response = unirest.get(url,header)
    #url and header is defined outside the function
    contents = response.raw_body
    for i in contents:
        print i['items']
        print i['profiles']

    return render(request,"profile_model.html",{})

我看到在调试模式下

Name:contents
Value:

str: {
  "items" : [ 13184519, 13184195, 13183948, 13184350, 13183946, 13184208],
  "profiles" : [ "slezyr", "stefek99", "amlib", "vyrotek", "xenophonf", "TheGrumpyBrit"]
}

我收到 TypeError:字符串索引必须是整数,而不是 str.If 我删除项目中的引号 我将得到未定义的变量 'items'

如果您的 reponse.raw_body 是字典,此代码将有效。如果它是一个列表,请添加回迭代代码。

def profile_model(request):
    response = unirest.get(url,header)
    #url and header is defined outside the function
    contents = json.loads(response.raw_body)

    print contents['items']
    print contents['profiles']

    return render(request,"profile_model.html",{})