遍历django模板中的json元素

iterate through json elements in django template

本文关键字:json 元素 django 遍历      更新时间:2023-09-26

这个问题已经被问了很多次并得到了回答,但这对我来说根本不起作用。我的json结构是:

{
   "apps": {
      "app": [
         {
            "logAggregationStatus": "SUCCEEDED", 
            "runningContainers": -1, 
            "allocatedVCores": -1, 
            "clusterId": 234234, 
            "amContainerLogs": "url", 
            "id": "1",  
            "finalStatus": "SUCCEEDED"
         }
      ]
   }
}

我从django视图返回一个json响应,如下所示:

def configuration(request):
 response = requests.get("http://my_url/") 
 job = response.json()
 return render_to_response("configuration.html", {"job": job})

我可以在我的configuration.html中看到响应对象为:

<tr>
  {% for app in job %}
    {{ job.apps.app }}
  {% endfor %}
</tr>

我的问题是我无法迭代剩余的。我想要app.id、app.finalStatus。我无法访问jobs.apps.app.id。我只能访问app.id,不能再访问了。

有人能帮帮我吗?

您的app包含一个dict列表,因此您需要在该列表上循环并获得每个dict:

<tr>
  {% for app in job.apps.app %}
    {{ app.id }}
    {{ app.finalStatus }}
  {% endfor %}
</tr>