如何使用python(django)访问mashape中的词典列表?

时间:2016-12-15 14:01:59

标签: python django mashape

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

1 个答案:

答案 0 :(得分: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",{})