我有字典,可以在这里https://jsoneditoronline.org/?id=a570322381fc45919a7a03ebad78cbee
但是根据我到目前为止所读的内容,它更有可能是字典列表。我正在尝试显示标题,描述,作者和类别等字典中的数据,但是模板标签未显示我想要的内容,尝试了循环但无法访问
尝试这样的循环
{% for items in books %}
{% for volumeInfo in items %}
{{ volumeInfo.title }}
{% endfor %}
{% endfor %}
{{books.items}}是唯一有效的方法,但是它给了我整个json,但我只需要几个值。
def api(request):
books = {}
if 'books' in request.GET:
books = request.GET['books']
url = 'https://www.googleapis.com/books/v1/volumes?q=%s' % books
response = requests.get(url)
books = response.json()
print(type(books))
with open("data_file.json", "w") as write_file:
json.dump(books, write_file)
return render(request, 'books/api.html', {'books': books})
{% load get_item from template_filters %}
{% block content %}
<h2>Google API</h2>
<form method="get">
<input type="text" name="book">
<button type="submit">search on google books api</button>
</form>
{% if books %}
<p>
{% for items in books %}
{% for volumeInfo in items %}
{{ volumeInfo.title }}
{% endfor %}
{% endfor %}
{{ books.items }}
</p>
{% endif %}
{% endblock %}
答案 0 :(得分:1)
您需要遵循所拥有JSON的结构。总结一下,数据看起来像这样:
{
"items": [
{
"volumeInfo": {
"title": "Hobbit czyli Tam i z powrotem"
}
}
]
}
因此,在模板中:
{% for item in books.items %}
{{ item.volumeInfo.title }}
{% endfor %}