Django:将Json数据解析为模板

问题描述:

只是想知道如何正确地将我的views.py函数中的json数据解析为模板,以便在我希望使用数据创建表并对其进行进一步迭代时可以在模板中对其进行访问.数据看起来像这样:

Just wondering how I correctly parse my json data from my views.py function to my template so it can be accessed within my templates as I am looking to create a table using the data and further iterate on it. Data looks like so :

{"meta": {"limit": 25, "cache-expiry": 3600}, "objects": [{"name": "Pizza Hut delivery", "locality": "Norwich", "website_url": null, "cuisines": [], "region": "Norfolk", "long": 1.27727303158181, "phone": "01603 488900", "postal_code": null, "categories": ["other", "restaurant"], "has_menu": false, "country": "United Kingdom", "lat": 52.6564553358682, "id": "00388fe53e4c9f5e897d", "street_address": null, "resource_uri": "/v1_0/venue/00388fe53e4c9f5e897d/"}, {"name": "Thai Lanna", "locality": "Norwich", "website_url": "http://www.thailannanorwich.co.uk", "cuisines": [], "region": "Norfolk", "long": 1.2788060400004, "phone": "01603 625087", "postal_code": "NR2 1AQ", "categories": ["other", "restaurant"], "has_menu": true, "country": "United Kingdom", "lat": 52.6273547550005, "id": "0452369b7789e15bb624", "street_address": "24 Bridewell Alley", "resource_uri": "/v1_0/venue/0452369b7789e15bb624/"},

我尝试使用url,但除了像这样简单地做外没有其他运气:

I have tried using urls but haven't had any luck beyond simply doing it like so:

return HttpResponse(json.dumps(data), content_type='application/json')

但这只是将整个json api数据打印到屏幕上.欢迎任何建议

but that simply prints the whole json api data to the screen. Any suggestions are welcome

您应使用

You should use loads() to decode the json string to the python data:

return render(request, 'my-template.html', json.loads(data))

或者,仅获取部分数据:

Or, to get only the part of the data:

decoded_data = json.loads(data)
return render(request, 'my-template.html',
                       {'objects': decoded_data['objects']})

然后在您的模板中执行以下操作:

And then in your template do something like this:

<ul>
{% for obj in objects %}
    <li>{{ obj.name }} - {{ obj.locality }}</li>
{% endfor %}
</ul>