Decode json and Iterate through items in django template Decode json and Iterate through items in django template django django

Decode json and Iterate through items in django template


Once you've used Python's json or simplejson module to load the JSON data into Python objects, everything should just work in your template.

Before sending things to your template I would pull out the results like so...

def foo_view(request):    ....    decoded_json = json.loads(json_string)    return render_to_response('foo.html',{'results':decoded_json['Result']})

That way in your template you'll be able to work on each result like so...

<ul id="results">     {% for result in results %}     <li>Result{{ forloop.counter }}: {{ result.URL }}, {{ result.PlaylistID }}, {{ result.Name }} ...</li>     {% endfor %}</ul>

The data in the output will appear in the same order as it did in the JSON array at Results. If you need to sort the data then you will need to do that in your view, NOT in your template.


You don't need to do any further pre-processing in Python before sending the dictionary to Django (beyond what you have already done; using simplejson to parse the JSON string into a dictionary). Django's templating system is very good at dealing with dictionaries and lists.

I will assume you have passed the dictionary to Django in a variable called obj.

You should be able to access each item in the Result part of the dictionary using a for loop:

<ul>{% for result in obj.Result %}    <li>{{ result.Url }}, {{ result.PlaylistID }}, {{ result.Name }}</li>{% endfor %}</ul>

For example, will place the results in a bulleted list, with the Url, Playlist and Name in a comma-separated list.