python - passing a list of dict in javascript Flask

Viewed 10673

I know how to pass a variable from Flask (python) to my template html file with {{data}}. However I am having trouble accessing each dictionary element and its respective key-value pairs in the list in javascript.

start.py

def func1():
        data = filter() #returns a list of dictionaries

    return render_template("template1.html", data=data)

template1.html

<html>
  <head>
  .....
  </head>
  <body>
    <p>This is html: {{data}}</p>

    <script type="text/javascript" src="{{url_for('static', filename='js/add.js') }}"></script>
    <script type="text/javascript">
    myvar = '{{data}}';
    document.write(myvar);

    </script>
  </body>

</html>

add.js

//code to be written here

myvar and This is html: both outputs out the entire list of dictionaries. I've already tried myvar[0] but that just outputs [ for some reason. I have also done:

myvar = '{{data|tojson}}';
var parsed = JSON.parse(myvar);
document.write(parsed[0]);

but that outputs [object Object].

2 Answers
Related