首页 > 解决方案 > Django:如何迭代包含字典的列表

问题描述

我得到 Json 数据,然后将其转换为 python 对象。这是代码:

    number = request.POST.get('num')
    url = "http://127.0.0.1:9000/findexclusive"
    querystring = {"num":number}
    response = requests.request("GET", url, params=querystring)
    response = response.json()
    response = json.loads(response)
    return render(request,'home.html',{'details':response})

现在我得到了一个有效的回应。但无法将此数据转换为 html 页面。我得到的数据如下:

[{u'pk': 1233, u'model': u'details.modelname', u'fields': {a': u'xyz', u'b': u'something', u'c': u'something', u'd': u''}}]

我如何迭代这个。

这些不起作用:

for data in b[0]:
...     for key,value in data.items:
...         print key
... 
Traceback (most recent call last):
  File "<console>", line 2, in <module>
AttributeError: 'unicode' object has no attribute 'items'
>>> a = data.json()

标签: djangopython-2.7django-templates

解决方案


当你这样做时,response[0]你已经得到了 dict 项目。所以for data in response[0]会给你字典键的列表。您可以使用:

for data in response:
     for key,value in data.items:
         print key

另请注意,您可以删除此行response = json.loads(response)。既然response = response.json()已经给你解码了 JSON。


推荐阅读