【问题标题】:How to parse, and render, json use in Flask template如何在 Flask 模板中解析和渲染 json 使用
【发布时间】:2014-12-26 14:43:34
【问题描述】:

这是我的 Flask 应用代码:

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()

还有来自index.html 模板的sn-p:

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

解析url地址发送一个HTTP GET请求,该请求已经被喷到屏幕上,然后它就会给出。在 JSON 中创建自定义以显示到对象。我通过在模板中插入一个数据项得到了 JSON 数据输出,但它没有出现在屏幕上。这有什么问题吗?

【问题讨论】:

    标签: python json templates flask


    【解决方案1】:

    假设data 是一个 JSON 对象而不是一个数组,则响应被翻译成 Python 字典。遍历字典返回,而不是值。这意味着您尝试访问字符串上的属性item(并且Python 中的字符串没有“item”属性)。有几种方法可以解决这个问题:

    {# 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 %}
    

    【讨论】:

    • 这看起来不对。 json.dumps' is a str` 对象的输出。您将收到如下错误:undefinedError: 'str object' has no attribute 'items'
    • 在这种情况下,datajson.loads 的结果,json.loads 是 Python 列表或字典,在这种情况下是字典。
    • @downvoter - 想解释什么是错的,以便纠正?
    • 错误...不起作用,抱歉 '14...没注意
    猜你喜欢
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    • 2018-06-05
    相关资源
    最近更新 更多