1

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?

kbdev
  • 1,225
  • 1
  • 13
  • 33

1 Answers1

6

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 %}
John Meinken
  • 439
  • 4
  • 10
  • Thank you! This does pull in the name. It seems to be having an issue still with hyphenated items though. `friendly-date` does not work because it cannot parse the remainder '-date'. – kbdev Sep 15 '17 at 20:45
  • Unfortunately, there's not an easy fix for that. The best solution would probably be a [custom template tag](https://stackoverflow.com/questions/8252387/how-do-i-access-dictionary-keys-that-contain-hyphens-from-within-a-django-templa). – John Meinken Sep 15 '17 at 20:56