I have a Python Flask web app that I want to pass a dictionary data set from to javascript, I am trying to JSON I can pass numbers fine but it seems to throw an error when using strings.
Here is the code snippet of the python generating the JSON string: view.py
def dumpdata():
DB_name={"name":"aaragh"}
strng=json.dumps(DB_name)
return render_template('dumpdata.html',result = strng)
Here is the receiving HTML file dumpdata.html
<html><body>
<p >{{ result }}</a>
<script>
var data = JSON.parse({{result}});
console.log(data.name);
</script>
</body></html>
Here is the error message and the console output: consolelog
SyntaxError: invalid property id dumpdata:4
<html><body>
<p >{"name": "aaragh"}</a>
<script>
var data = JSON.parse({"name": "aaragh"});
console.log(data.name);
</script>
</body></html>
I dont think it's relevant but I get the same error on both ubuntu chrome and win IE.
Any ideas? I think I am missing something obvious but I have banged my head against this for days and I still haven't been able to find a solution...
Thanks
Take a look at the template filter |safe
:
<html><body>
<p >{{ result|safe }}</a>
<script>
var data = JSON.parse({{ result|safe }});
console.log(data.name);
</script>
</body></html>
Flask docs mention
Jinja docs mention
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With