簡體   English   中英

Django:將Json數據解析為模板

[英]Django : Parsing Json data to template

只是想知道如何正確地將我的json數據從views.py函數解析為模板,以便在我希望使用數據創建表並對其進行進一步迭代時可以在模板中對其進行訪問。 數據如下所示:

{"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,但是除了像這樣簡單地做之外沒有其他運氣:

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

但這只是將整個json api數據打印到屏幕上。 歡迎任何建議

您應該使用loads()將json字符串解碼為python數據:

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

或者,僅獲取部分數據:

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM