python - python django 中的 JSON 消耗

标签 python json django django-templates django-rest-framework

这是我得到的 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/

相关文章:

python - 在 mod_wsgi 下运行 Django 站点

python - Django mongoengine 不连接到远程服务器,总是连接到本地主机

python - Spyder、matplotlib 和 prints 中的子进程不起作用

python - 如何为 python 3.0 的仅关键字参数导入 __future__?

json - 如何在 golang 中轻松编辑 JSON 类型(如 Node.js)

python - Factory Boy 日期提供程序正在返回字符串

python - 密码生成器的字符顺序如何随机化

python - 用 python 查看 A 和上一个 B

json - 如何正确地将带有DateTime的PSObject序列化为JSON?

javascript - Typeahead Bootstrap 返回 ID 和值 Json