1

I am trying to get a "json" object from a python dictionary using djnago template "json_script",which is throwing "template syntax error"

//html code
{{ value|json_script:"hello-data" }}

<script>
var Value=JSON.parse(document.getElementById("hello-data").textContent);
document.write(Value);
</script>


//views.py
from django.shortcuts import render
from django.http import HttpResponse
import random as ran
# Create your views here.

def indees(request):
vals={"123":"abc","Key":"value","hello":"user"}
return render(request,"verbat.html",context={"value":vals})

1 Answers1

2

The context is the template context dictionary, you cannot access it as a single dict, you can only access its members (keys). Read here or here for more.

E.g., In your example, you can access 'bool', 'list_' and 'msg', but probably you want to access a dictionary with these three keys.

So you need to put your data inside inner key and use it. Something like:

//views.py
def indes(request):
  list_of_vals=[ran.randint(12,34),ran.randint(44,55)]
  data={"bool":"True",
        "list_":list_of_vals,
         "msg":"hello"}
  return render(request,"base.html",context={'data':data})

And inside index.html, to have:

{{ data|json_script:"hello-data" }}
eran
  • 6,731
  • 6
  • 35
  • 52
  • thank you for your info! but still it is not working. I tried assigning the dictionary to context and accessed context variable in jsp, it is still saying template_syntax error – Maneesha Shetty May 07 '19 at 07:57
  • It worked for me fine. can you post your full code? – eran May 07 '19 at 09:38
  • 1
    json_script is only from django 2.1 https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#json-script, maybe you are using older version? Because with new django it works fine for me – eran May 07 '19 at 10:15