0

I am sending a URL as request and in response I am getting back a list of dictionary and I am unable to loop through the values.

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

In debug mode I am seeing

Name:contents
Value:

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

I am getting TypeError: string indices must be integers, not str.If I remove quotes in items I will get undefined variable 'items'

Kiran
  • 1,481
  • 6
  • 36
  • 66
  • i think you are not parsing the request/response object back into json. json.loads(data) and then use key to access it. – Vikash Singh Dec 15 '16 at 14:04

1 Answers1

0

This code will work if your reponse.raw_body is a dictionary. If its a list do add back the iteration code.

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",{})
Vikash Singh
  • 13,213
  • 8
  • 40
  • 70