suhyun
suhyun

Reputation: 31

How to parse, and render, json use in Flask template

Here's my Flask app code:

from flask import render_template, jsonify
import requests
from app.test_blueprint import app


@app.route('/')
def index():

    url = 'http://api.address'
    response = requests.get(url)
    data = response.json()

    return render_template('index.html', data=data)


    if __name__ == '__main__':
        app.run()

And a snippet from the index.html template:

 <div class="title">
 {% for item in data %}
     <span>{{ item.title }}</span>
 {% endfor %}
 </div>

parsing the url address to send an HTTP GET request which has been sprayed on the screen , and then it will give . In JSON to create customized to show to object. I got the JSON data output by inserting a data item in the template , but it does not appear on the screen. Is any part of this wrong?

Upvotes: 3

Views: 21981

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 159875

Assuming data is a JSON object not an array, the response is being translated into a Python dictionary. Iterating over a dictionary returns the keys, not the values. This means that you try to access the attribute item on a string (and strings in Python don't have an "item" attribute). There are several ways you could fix this:

{# 1. Use the key to access the value from data #}
{% for key in data %}
  {{ data[key].item }}
{% endfor %}

{# 2. Explicitly enumerate the values #}
{% for value in data.values() %}
  {{ value.item }}
{% endfor %}

{# 3. Enumerate key-value pairs #}
{% for key, value in data.items() %}
  {{ value.item }}
{% endfor %}

Upvotes: 3

Related Questions