Question

Hello, i am relatively new to Python & Django.

My Problem:

resp, content = httplib2.Http().request("http://api.xxxxx.com/api/" + username)
str_content = content.decode('utf-8')
user = json.loads(str_content)

i return the user string and try to use that on my template, the json looks like that:

{
    "XXXXXX": {
    "bans": 6,
    "ban_info": {
        "randomrandomrandom": "randomrandomrandom",
        "randomrandom": "randomrandomrandomrandom"
    }
}

how can i rotate through these items and access the random informations?

like: user['bans'] returns 6

but how do i get these random things? user['ban_info']['???'] should return


My English is not the best, sorry for that. I hope i described my problem good enough!

Thanks for every help on that topic, i also hope, that this is not a duplicate!

Was it helpful?

Solution 2

How about a for loop?

for x in user['ban_info']:
    print x

For keys and values:

for (k, v) in user['ban_info'].iteritems():
    print k
    print v

OTHER TIPS

Iterating over a dict returns its keys, for example:

pizza = {"cheese": "mozarella",
         "topping": "pepperoni"}

for key in pizza:
    print pizza[key]

# outputs: mozarella
#          pepperoni

In your example you can simply do:

for key in user['ban_info']:
    print user['ban_info'][key]

From the views.py you should send a response with a dict of objects or in your case, the user object itself, like:

HttpResponse(simplejson.dumps(user), mimetype='application/json')

In your template you can access that dict with Django template tags like:

{{user.bans}}

Or iterate over a child array like:

{% for info in user.ban_info %}
    {{ info }}
{% endfor %}

or

{% for key, value in user.ban_info %}
    {{ key }}: {{ value }}
{% endfor %}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top