'Rendering a string in django template as json object

I have a angular app that sends json data to a django backend. The django app save the json data in to a DB and later pulls it out to send it back to the angular app. I am having trouble getting this whole chain to work right.

Here is where view to pass the json data back to the template.

def myview(request, uid):
    formrecord = FormData.objects.get(someid = uid)
    return render(request, 'myview.html', 'formdata':formrecord.data})

Here is what formrecord.data looks like before render() above gets called:

(Pdb) formrecord.data
u'{"user":{"firstName":"Bob","lastName":"Henderson"}}'

Here is my template

<script>
var mydata ={{ formdata }};
mydata = JSON.parse(mydata);
console.log(mydata);
</script>

Here is what gets rendered:

var mydata ={&quot;user&quot;:{&quot;firstName&quot;:&quot;Bob&quot;,&quot;lastName&quot;:&quot;Henderson&quot;}};

The JSON.parse(mydata) gives me a syntax error on the JS side. How I can get the JS to parse the string correctly into a JS object?



Solution 1:[1]

The value of mydata is not a string, you don't need to parse it as it's already a valid JS object: var mydata ={"user":{"firstName":"Bob","lastName":"Henderson",}};

You can go ahead and access properties like: mydata.user.firstName

Also, you should validate the JSON data you're storing in your model. The data you posted above is not valid, as in JSON the trailing comma is illegal.

Solution 2:[2]

As @Arsh Singh said, formrecord.data is not a valid json, bit it's a valid dict for python, you can try like this:

# views
import json

def myview(request, uid):
    formrecord = FormData.objects.get(someid = uid)
    jsondata = json.dumps(formrecord.data)
    return render(request, 'myview.html', 'formdata':jsondata})

And then in JS block

<script>
  var mydata ={{ formdata }};
  console.log(mydata);
</script>

Solution 3:[3]

You must use `|safe' in your JS file like below:

views

import json

def myview(request, uid):
    formrecord = FormData.objects.get(someid = uid)
    jsondata = json.dumps(formrecord.data)
    return render(request, 'myview.html', 'formdata':jsondata})

And then in JS block

<script>
  var mydata ={{ formdata|safe }};
  console.log(mydata);
</script>

Solution 4:[4]

in js block use

<script>
  var mydata = JSON.parse("{{formdata|escapejs}}");
  console.log(mydata);
</script

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arsh Singh
Solution 2 Gocht
Solution 3 henrry
Solution 4 Santosh Premi Adhikari