【问题标题】:Parse json into html template将 json 解析为 html 模板
【发布时间】:2016-12-27 20:29:17
【问题描述】:

我从数据库中选择了一行包含一些 json 内容的行

我的功能选择行

@route('/list')
def list():
    c = conn.cursor()
    c.execute("SELECT content FROM pages WHERE URL = 'blob.com'")
    select = c.fetchall()
    return template('views/list.tpl', rows=select)

“内容”行的结果是:

{ "ruleGroups": { 
    "SPEED": { "score": 97 } 
                }, 
    "pageStats": { "numberResources": 3, 
                   "numberHosts": 2, 
                   "totalRequestBytes": "500", 
                   "imageResponseBytes": "3148", 
                   "otherResponseBytes": "3838" 
                 }, 
    "screenshot": { "mime_type": "image/jpeg", 
                    "data": "imgcontent", 
                    "width": 320, 
                    "height": 240, 
                  } 
} 

我想从json“score”、“numberResources”和“numberHosts”中显示在list.tpl中。

我应该如何处理 list.tpl?

【问题讨论】:

  • 我不确定我是否理解,也许:content['ruleGroups']['SPEED']['score']; content['pageStats']['numberResources']; content['pageStats']['numberHosts']?

标签: python json templates bottle


【解决方案1】:

在您的模板中执行以下操作:

    % for row in rows:
        % for key, value in row.iteritems():
            %if key == 'ruleGroups':
                <p>SCORE: {{value['SPEED']['score']}}</p>
            %elif key == 'pageStats':
                <p>Number of resources: {{value['numberResources']}}</p>
                <p>Number of hosts: {{value['numberHosts']}}</p>
            %end
        %end
    %end

【讨论】:

    猜你喜欢
    • 2016-11-13
    • 2021-12-26
    • 2010-12-31
    • 2019-10-14
    • 2020-06-14
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    相关资源
    最近更新 更多