这是我得到的 json 输出 -
{
"count": 2,
"next": null,
"previous": null,
"check": [
{
"url": "http://127.0.0.1:8000/app_name/cities/1/persons/?format=json",
"id": 1,
"name": "City1"
},
{
"url": "http://127.0.0.1:8000/app_name/cities/2/persons/?format=json",
"id": 2,
"name": "City2"
}
]
}
我正在使用下面给出的 View -
def get_name(request):
data = requests.get('http://127.0.0.1:8000/app_name/cities/?format=json')
context = RequestContext(request, {
'cities': data.check,
})
return render_to_response('template', context)
能够像这样在我的模板中使用这些数据 -
template.html
{% block names %}
{% for city in cities %}
<a href="{% url 'next_view_name' city.id %}"><p>{{city.name}}</p></a>
{% endfor %}
{% endblock %}
但是,这给了我以下错误 -
“Response”对象没有属性“check”
返回json数据字典值的正确流程是怎样的?
最佳答案
您正在尝试操作来自请求的响应对象。您需要先将其包含的 json 字符串覆盖到一个对象中,然后才能执行其他操作:
def get_name(request):
data = requests.get('http://127.0.0.1:8000/app_name/cities/?format=json')
data = data.json() # <-- convert the json to an object
context = RequestContext(request, {
'cities': data['check'],
})
return render_to_response('template', context)
关于python - python django 中的 JSON 消耗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34304311/