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 Answer 1

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" }}
Sign up to request clarification or add additional context in comments.

3 Comments

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
It worked for me fine. can you post your full code?
json_script is only from django 2.1 docs.djangoproject.com/en/2.2/ref/templates/builtins/…, maybe you are using older version? Because with new django it works fine for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.