admin管理员组文章数量:1355529
I am using python flask temple to build a site. I have a case where I want to send a python list to a java script. The python list contains three objects however when I do list1.length in the java script environment I see the length of this list is 23. This is most likely because java script is identifying it as a string. My question is how to make the python list stay a list once it's passed into javascript ?
# my route with python list1
@app.route('/chart_sandbox')
def chart_sandbox():
list1 = ['abc', 'def', 'hij']
return render_template("chart_sandbox.html", list1=json.dumps(list1))
# My Java script
<script type="text/javascript">
var list1 = '{{list1|tojson}}'
var listLength = list1.length
document.write(listLength)
document.write(list1)
</script>
# this is what is returned to me. As you can see java script length is seen
#as 23 instead of 3
23"["abc", "def", "hij"]"
I am using python flask temple to build a site. I have a case where I want to send a python list to a java script. The python list contains three objects however when I do list1.length in the java script environment I see the length of this list is 23. This is most likely because java script is identifying it as a string. My question is how to make the python list stay a list once it's passed into javascript ?
# my route with python list1
@app.route('/chart_sandbox')
def chart_sandbox():
list1 = ['abc', 'def', 'hij']
return render_template("chart_sandbox.html", list1=json.dumps(list1))
# My Java script
<script type="text/javascript">
var list1 = '{{list1|tojson}}'
var listLength = list1.length
document.write(listLength)
document.write(list1)
</script>
# this is what is returned to me. As you can see java script length is seen
#as 23 instead of 3
23"["abc", "def", "hij"]"
Share
Improve this question
asked May 27, 2017 at 20:20
Max PowersMax Powers
1,1995 gold badges28 silver badges58 bronze badges
3 Answers
Reset to default 7Remove the quotes around the jinja text. That's converting your list into a string-representation of a list. Something like this should work:
var list1 = {{ list1 | tojson }};
This worked me, I wrapped the list with the or operation and tojson in double curly brackets as an argument in the JSON.parse function, to make it a JavaScript object.
let list1 = JSON.parse('{{ list1 | tojson }}');
If you have no plans to modify the data in JavaScript use this instead
本文标签: flask python list to javascriptStack Overflow
版权声明:本文标题:flask python list to javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743938180a2565071.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论