首页 > 解决方案 > jinja2.exceptions.UndefinedError:列表对象没有元素 1

问题描述

"artists": {
        "href": "https://api.spotify.com/v1/search?query=Hozier&type=artist&offset=0&limit=20",
        "items": [
          {
            "images": [
              {
                "height": 640,
                "url": "https://i.scdn.co/image/2e4114631a20bd71903bc335b88f872afdce9a33",
                "width": 640
              },
              {
                "height": 320,
                "url": "https://i.scdn.co/image/4d4be818dc98d47b9086ecff8ec4883902781070",
                "width": 320
              },
              {
                "height": 160,
                "url": "https://i.scdn.co/image/c181b6184e82bd7f8411d97b87e4f1daa1bbbbb8",
                "width": 160
              }
            ]
          }
        ]
      }

我正在尝试使用 jinja2 访问第二个字典中 url 键的值,问题是每次我运行网页时它都会给我一个状态码500,并且在终端中仔细查看它会给我一个jinja2.exceptions.UndefinedError: list object has no element 1但那没有对我来说没有意义,因为它打印{{value[1]}}得很好。当我尝试遍历该字典的键和值时,就会出现问题。

以下是我的 jinja2 代码。如果您能指出我做错了什么或我在这里遗漏了什么,那将不胜感激。

{% if q_type == "artist" %}
    {% for record in results['artists']['items'] %}
        {% for key, value in record.items() %}
            
            {% if key == "images" %}
                {% for k, v in value[1].items() %}
                    {% if k == "url" %}
                        {{info.append(v) or ""}}
                    {% endif %}
                {% endfor %}
            {% endif %}

        {% endfor %}
    {% endfor %}
{% endif %}

标签: jsonjinja2

解决方案


推荐阅读