如何在JavaScript中循环遍历一个字典列表

huangapple go评论69阅读模式
英文:

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 }};

huangapple
  • 本文由 发表于 2023年3月21日 02:48:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75794177.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定