英文:
How to loop through a list of dictionaries in JavaScript
问题
这是您要翻译的部分:
I have an SQL request that gives me all the data I need (in Python)
I made it so that I have a list of dictionaries, it looks like that:
data = [{
"jour_de_la_semaine": "0",
"nom_rue": "Avenue Rogier",
"total_lourd": 4464.676489954501,
"total_pieton": 366.75719346780005,
"total_velo": 1530.4361518144,
"total_voiture": 16283.220910553997
}, {
"jour_de_la_semaine": "1",
"nom_rue": "Avenue Rogier",
"total_lourd": 4689.496674622601,
"total_pieton": 719.5071498280998,
"total_velo": 6835.787324285102,
"total_voiture": 22114.002369259702
},
...,
...]
这段代码描述了一个包含字典的列表。这些字典包含了不同的数据,但您在JavaScript中处理它们时遇到问题。
英文:
I have an SQL request that gives me all the data I need (in Python)
I made it so that I have a list of dictionaries, it looks like that:
data = [{
"jour_de_la_semaine": "0",
"nom_rue": "Avenue Rogier",
"total_lourd": 4464.676489954501,
"total_pieton": 366.75719346780005,
"total_velo": 1530.4361518144,
"total_voiture": 16283.220910553997
}, {
"jour_de_la_semaine": "1",
"nom_rue": "Avenue Rogier",
"total_lourd": 4689.496674622601,
"total_pieton": 719.5071498280998,
"total_velo": 6835.787324285102,
"total_voiture": 22114.002369259702
},
...,
...]
I put the variable in the return template so that I can use it on JavaScript.
I'm using this to do the list in JavaScript:
var data = '{{ all_data_rue|tojson }}';
I can easily see all the data with a simple console.log(data);
but its impossible for me to loop through it... It always return me characters per characters.
I've tried every single solutions I could find on the Net. I've also find a post where it has the exact same problem but the solution didn't work...
I'd like to get dictionaries per dictionaries and not characters per characters.
Any solution?
答案1
得分: 1
你正在将 data
设置为 all_data_rue
的字符串表示。如果你想从 JavaScript 中访问信息,可以这样做:
var data = {{ all_data_rue|tojson|safe }};
英文:
By doing
var data = '{{ all_data_rue|tojson }}';
You are setting data
to a string representation of all_data_rue
. If you want to access the information from Javascript, you can do
var data = {{ all_data_rue|tojson|safe }};
答案2
得分: 0
替代:
let data = JSON.parse('{{ all_data_rue|tojson }}');
或者简单地:
let data = {{ all_data_rue|tojson }};
英文:
Instead of:
var data = '{{ all_data_rue|tojson }}';
Try:
let data = JSON.parse('{{ all_data_rue|tojson }}');
or even just:
let data = {{ all_data_rue|tojson }};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论