2016-12-15 65 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",{})