kbdev
kbdev

Reputation: 1315

Iterate through JSON data in Django template

I am having trouble iterating through some JSON data that I managed to import into my Django Wagtail project. I want to list travel advisories on a website that are pulled in from here: http://data.international.gc.ca/travel-voyage/index-updated.json

I was able to do this in my model like so:

import requests

def get_context(self, request):
    response = requests.get('http://data.international.gc.ca/travel-voyage/index-updated.json')
    json_response = response.json()

    data = json_response['data']

    context = super(TravelAdvisoriesPage, self).get_context(request)
    context['data'] = data

    return context

I am now unsure of how to get the data into my template. I am able to pull in all of the data using {{ data }}.

But how do I pull out specific items from that JSON data? I want to grab both the English and French name, url-slug, advisory-text, etc. And all of those are nested within data > country code > language > item within the JSON structure.

I have tried something like:

{% for country in data %}
  {{ data[country].eng.name }}<br />
{% endfor %}

This is giving me errors like Could not parse the remainder: '[country].eng.name' from 'data[country].eng.name'. How do you grab these in the template?

Upvotes: 2

Views: 10556

Answers (1)

John Meinken
John Meinken

Reputation: 469

Django templates have their own syntax different from Python syntax. The brackets notation you're using in {{ data[country].eng.name }} isn't allowed. Use the items dictionary function to iterate over both the dict key and the dict value:

{% for country_key, country_value in data.items %}
  {{ country_value.eng.name }}<br />
{% endfor %}

Upvotes: 8

Related Questions