将Json数据解析为模板

将Json数据解析为模板

本文介绍了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

推荐答案

您应使用 loads() 将json字符串解码为python数据:

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>

这篇关于Django:将Json数据解析为模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 09:47