Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing Python Flask JSON dictionary into javascript error

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 >{&#34;name&#34;: &#34;aaragh&#34;}</a>
<script>
var data = JSON.parse({&#34;name&#34;: &#34;aaragh&#34;});
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

like image 543
tuetates Avatar asked Nov 17 '14 22:11

tuetates


1 Answers

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

like image 199
Celeo Avatar answered Oct 10 '22 00:10

Celeo