django - 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()
解决方案
当你这样做时,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。
推荐阅读
- node.js - 错误:找不到模块 - 在本地工作但不在 Heroku 上
- react-native - 使用本机反应导航
- java - struts2 JSP Ajax 调用
- angular - mat-tab 标签在短时间被选中时会移动。如何解决这个问题
- javascript - AG-Grid(企业)列菜单监听器
- r - 安装 github 项目的错误信息
- swift - 保存后 NSManagedContext 变为 nil
- scala - 使用 AWS s3 的分段上传 API 时出现内存不足问题
- android - Android- 两个依赖库产生冲突,
- excel - 不工作时做例外,循环永不停止