Facing problem passing json data to .html file


(Saurabh Kapoor) #1

in views.py

def work(request,th,sg):
    text={0 : 'hello' , 1 :'hi' }
    return render(request,'mainpage/work.html', { 'hello': "hello " , 'jsn': json.dumps(text) } )

in .html

{{hello}}
<p id="demo"></p>
<script>
var txt= {{ jsn | safe }}
document.getElementById("demo").innerHTML = txt;
</script>

output

hello 
[object Object]

I have to pass a dictionary in which there is a key and a value and the dictionary holds a key which has json data . So i want to know is it possible to render a dictionary in which we can pass multiple dictionary value or a set of dictionary and amond those json objects. So can we pass a dictionary with multiple json object and another dictionary


(Vitor Freitas) #2

Try to put quote marks around the {{ jsn | safe}}, like this:

{{hello}}
<p id="demo"></p>
<script>
var txt= "{{ jsn | safe }}";
document.getElementById("demo").innerHTML = txt;
</script>

That’s because you are using the Django template system to render a JS code, and Django will render the jsn content as plain text. You need to add the quote marks to tell JS that this is a string.


(Saurabh Kapoor) #3

thank you for replying