2016-12-15 38 views
0

我发送一个URL作为请求,作为回应,我收回了一个字典列表,我无法循环访问这些值。如何使用python(django)访问mashape的字典列表?

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"] 
} 

我得到类型错误:字符串索引必须是整数,而不是str.If我删除项目的报价,我会得到不确定的变量“项目”

+0

我认为你不会将请求/响应对象解析回json。 json.loads(data),然后用键来访问它。 –

回答

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",{})