john doe
john doe

Reputation: 11

Unable to use JSON.parse in my django template

I have a variable data1 in my Django view which has been returned in the following way -

def dashboard(request):
   df1 = pd.read_excel("file.xlsx")
   str1= df1.to_json(orient = 'records')
   data1 = json.loads(str1)
   return render(request, 'dashboard/new 1.html',{'data1' : data1})

The variable is then called in the template using javascript

 <script type = text/javascript>    
   var ob2 = JSON.parse( {{ data1 }} );
   document.write(ob2);
 </script>

This does not show anything on the HTML webpage created. Is there anything wrong in the code?

Upvotes: 1

Views: 347

Answers (3)

itzMEonTV
itzMEonTV

Reputation: 20369

Try this by remove Parse

 <script type = text/javascript>    
   document.write("{{ data1 }}");
 </script>

Upvotes: 0

Adam Hopkins
Adam Hopkins

Reputation: 7102

Try outputting it as a string:

<script type = text/javascript>    
  var ob2 = JSON.parse( "{{ data1 }}" );
  document.write(ob2);
</script>

If this is not producing the results, I suggest just printing {{ data1 }} on screen and seeing exactly what is being returned by Django.

Upvotes: 1

RemcoGerlich
RemcoGerlich

Reputation: 31270

Besides The Brewmaster's answer, the other problems are:

data1 = json.loads(str1)

That turns the JSON string back into a Python data structure. Just send str1 itself to the template, and call it a as that's what you use in the template:

return render(request, 'dashboard/new 1.html',{'a' : str1})

Upvotes: 1

Related Questions