通过Django模板中的json列表进行迭代

时间:2017-09-15 13:29:11

标签: python json django list jinja2

我在Django模板中传递了以下上下文:

context = {'test': custom_json_list}

custom_json_list的输出是这样的:

{'pc_16530587071502': [{'people_count_entry__sum': None}],
 'pc_17100675958928': [{'people_count_entry__sum': None},
                       {'people_count_entry__sum': None},
                       {'people_count_entry__sum': None},
                       {'people_count_entry__sum': None},
                       {'people_count_entry__sum': None},
                       {'people_count_entry__sum': None},
                       {'people_count_entry__sum': None},
                       {'people_count_entry__sum': None},
                       {'people_count_entry__sum': 4},
                       {'people_count_entry__sum': None},
                       {'people_count_entry__sum': None},
                       {'people_count_entry__sum': None},
                       {'people_count_entry__sum': None},
                       {'people_count_entry__sum': None},
                       {'people_count_entry__sum': None},
                       {'people_count_entry__sum': None}]} 

我想以下列格式显示数据:

'pc_16530587071502' : NONE
'pc_17100675958928' : None
'pc_17100675958928' : None
'pc_17100675958928' : None
'pc_17100675958928' : None
'pc_17100675958928' : None
'pc_17100675958928' : None
'pc_17100675958928' : 4
'pc_17100675958928' : None
'pc_17100675958928' : None
'pc_17100675958928' : None

如何继续语法,以便以这种格式查看数据。

我唯一能够破译的是:

{% for key, value in test.items %}
     {{ key }} <br />
     {{ value }} <br />
{% endfor %}

提前致谢。

1 个答案:

答案 0 :(得分:4)

你走在正确的轨道上。您需要做的就是遍历value

{% for key, value in test.items %}
    {% for dct in value %}
        {% for k, sum in dct.items %}
            {{ key }}: {{ sum }} <br />
        {% endfor %}
    {% endfor %}
{% endfor %}