[Fixed]-Rendering a string in django template as json object

0👍

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.

1👍

in js block use

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

0👍

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>
👤Gocht

0👍

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>
👤henrry

Leave a comment