0

我正在发送一个 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。如果我删除项目中的引号,我将得到未定义的变量“项目”

4

1 回答 1

0

如果您的 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",{})
于 2016-12-15T14:06:35.790 回答