【问题标题】:JSON consumption in python djangopython django中的JSON消费
【发布时间】:2016-03-22 03:13:14
【问题描述】:

这是我得到的 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"
    }
]
}

我正在使用下面给出的视图-

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' object has no attribute 'check'

json数据返回字典值的正确流程是什么?

【问题讨论】:

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


    【解决方案1】:

    您正试图操纵来自请求的响应对象。您需要先将其包含的 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)
    

    【讨论】:

    • 我仍然收到同样的错误'dict' object has no attribute 'results'
    • 很抱歉,我的意思是在发帖之前我已经尝试过了,但我遇到了这个错误,我不知道如何获取 results 中的所有值。谢谢。
    • 我现在收到了TypeError: string indices must be integers
    • data.text 的输出是什么?
    猜你喜欢
    • 2016-03-30
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    • 2023-03-20
    • 2020-08-15
    • 1970-01-01
    相关资源
    最近更新 更多