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

16,294

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 %}
Share:
16,294

Related videos on Youtube

suhyun
Author by

suhyun

Updated on June 05, 2022

Comments

  • suhyun
    suhyun almost 2 years

    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?

  • Pradeep
    Pradeep about 7 years
    This is not looking right. the output of a json.dumps' is a str` object. You will get an error like so: undefinedError: 'str object' has no attribute 'items'
  • Sean Vieira
    Sean Vieira about 7 years
    In this case, data is the result of a json.loads which is a Python list or dictionary, and in this case, a dictionary.
  • Sean Vieira
    Sean Vieira almost 6 years
    @downvoter - care to explain what is wrong so it can be corrected?
  • M. Mariscal
    M. Mariscal almost 4 years
    Error... doesnt work, sorry on '14... didnt pay attention