最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - passing a list of dict in javascript Flask - Stack Overflow

programmeradmin0浏览0评论

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].

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].

Share Improve this question edited Jul 16, 2017 at 19:35 LeggoMaEggo asked Jul 16, 2017 at 19:26 LeggoMaEggoLeggoMaEggo 5311 gold badge9 silver badges25 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 14

By placing data in single quotes you are creating a string. To get python data types into JavaScript, serialize them with {{ data | tojson }}.

var parsed = JSON.parse('{{data | tojson}}');

You may need to escape the output with safe filter. See more at sending data as JSON object from Python to Javascript with Jinja

Got it!

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

Outputs the [object Object] which is the dictionary at the position. So then all you need to do is document.write(parsed[0].name); to access its name value!

发布评论

评论列表(0)

  1. 暂无评论