Jinja2 - How to loop a json list?

后端 未结 2 1789
走了就别回头了
走了就别回头了 2021-02-03 10:41

How can I loop a json list with jinja2?

I have this json list,

[
    {
        \"first_name\": \"John\",
        \"last_name\": \"Smith\",
        \"user         


        
2条回答
  •  别跟我提以往
    2021-02-03 11:28

    your json list contains dictionaries; you need to access the dictionary elements differently than you would class members; try:

    {{ user['first_name'] }}
    

    this works for me (python 3.4 and python 2.7)

    import json
    from jinja2 import Template
    
    json_str = '''[{"first_name": "John", "last_name": "Smith", "user_id": 4, 
        "address": null}, {"first_name": "Jane", "last_name": "Heart",
        "user_id": 5, "address": null}, {"first_name": "Dom",
        "last_name": "Robinsons", "user_id": 6, "address": null},
        {"first_name": "Pete", "last_name": "Hand", "user_id": 7,
        "address": null}]'''
    
    users = json.loads(json_str)
    
    tmpl = Template('''
    
       {% for user in users %}
       
       {% endfor %}
    
    {{ user['first_name'] }}
    ''') print(tmpl.render(users = users))

    output:

    John
    Jane
    Dom
    Pete

提交回复
热议问题