1

I have a json that looks like this

{    
        "values": {
            "a": 1,
            "b": 2,
            "c": 3,
            "d": 4
        },
    "sales-year": [
        { "a": 0, "b": 0, "c": 0, "d": 0, "e": "karl" },
        { "a": 0, "b": 0, "c": 0, "d": 0, "e": "karl" },
        { "a": 4, "b": 10, "c": 20, "d": 30, "e": "karl" },
        { "a": 0, "b": 0, "c": 0, "d": 0, "e": "karl" }
    ]
}

And I pass it through get_context_data with django to my 'index.html'. Further explanation here

I can access the values pretty easy with {{my_json.values.a}} However I am having problems accessing the sales-year array. How do I do that? I tried the following, none of them work:

{{my_json['sales-this'].2.a}} 
{{my_json.['sales-this'].2.a}} 
{{my_json.[sales-this].2.a}} 
{{my_json[sales-this].2.a}}
Community
  • 1
  • 1
Tom
  • 2,545
  • 5
  • 31
  • 71

1 Answers1

2

you need to create a custom template filter to handle this

First create a custom template filter like:

from django import template
register = template.Library()

@register.filter
def getItem(dict, key):
    return dict.get(key)

next in your template do like:

{{my_json|getItem:'sales-year'}} 

Learn more on how to use/create custom filters here

Anush Devendra
  • 5,285
  • 1
  • 32
  • 24