1

I have a JSON file that looks like this

{    
        "values": {
            "a": 1,
            "b": 2,
            "c": 3,
            "d": 4
        },
    "sales": [
        { "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 am importing that via get_context_data

import json
class MyCreateView(CreateView):

    def get_context_data(self, **kwargs):
        context = super(MyCreateView, self).get_context_data(**kwargs)

        with open('/path/to/my/JSON/file/my_json.cfg', 'r') as f:
                    myfile = json.load(f)
                    context['my_json'] = my_data

which works, when I do print myfile["sales"][0]["a"] I get 0 and when I put {{my_json}} into the index.html then I get the whole array.

So now my question is how to read the values best. Do I have to create context variables for each of the values or is it possible to read the json array in my html?

I tried {{my_json["sales"][0]["a"]}} but didn't work

Tom
  • 2,545
  • 5
  • 31
  • 71

1 Answers1

1

If you want to get myfile["sales"][0]["a"] in template you can do like:

{{my_json.sales.0.a}}

or if you want to get myfile["values"]["a"] this can be done like:

{{my_json.values.a}}
Anush Devendra
  • 5,285
  • 1
  • 32
  • 24
  • 1
    Just a note- this won't work if your keys have spaces in them. If you need to be able to do lookups by keys with spaces, you'll need a custom template tag, see here for more details: http://stackoverflow.com/questions/8000022/django-template-how-to-lookup-a-dictionary-value-with-a-variable – Joseph Dec 02 '15 at 18:33
  • ok I see, thank @Joseph. This works for my case. I was wondering, what do I write when I have `sales-this` instead of `sales`. I am having problems with the dash, I tried adding brackets and quotes. Any idea? – Tom Dec 02 '15 at 18:37
  • 1
    My guess is that, like a space character, you'll need to use a custom tag. Accessing dict values with the dot lookup is pretty limited (by design) in Django templates. Personally I don't agree with it, but that's what the Django core team has decided from a design perspective. – Joseph Dec 02 '15 at 18:42