0

I have a view that retrieves a JSON file like this:

json_lang = requests.get('path/to/file.json').json()
return render(request, "chat/chatroom.html", {'jsonLang': json.dumps(json_lang)})

Let's say the json file is structured somewhat like this:

{
    "en": {
        "action.send": "Send",
        "chat.joined": "joined the chatroom",
        "chat.left": "left the chatroom",
...
}

If I try to access one of those strings in a template like this {{ jsonLang.en.chat.joined }} I get an empty output.

Other methods, like trying to access it like this jsonLang["en"]["chat.joined"] result in an error:

TemplateSyntaxError at /chat/
Could not parse the remainder: '["en"]["chat.joined"]' from 'json_lang.["en"]["chat.joined"]'

What's the correct method to do this?

Samuele B.
  • 481
  • 1
  • 6
  • 29

1 Answers1

2

Firstly, 'jsonLang': json.dumps(json_lang) means that you pass a string to template. You should use 'jsonLang': json_lang to pass it as a Python dictionary.

Secondly, as dictionary lookup in Django templates are implemented with dot notation, this breaks if the key itself contains a dot.

One solution is adding a quick template filter that allows to access dictionary items by keys with dots - Access a dictionary element in the Django template with a variable

edgars
  • 1,038
  • 1
  • 7
  • 17
  • 1
    I tried with a key that doesn't contain a dot: I still get an empty output – Samuele B. Jul 14 '20 at 22:21
  • I have to note that if I use ```{{ jsonLang }}``` I do get an output: the whole json file. Trying to acces any key in that file results in empty output. – Samuele B. Jul 14 '20 at 22:22