Flask 要传递到模板的非嵌套JSON列表
我正在查询我的数据库,并将所有结果分配给名为Flask 要传递到模板的非嵌套JSON列表,flask,Flask,我正在查询我的数据库,并将所有结果分配给名为reports results = db.engine.execute("SELECT * FROM reports") reports = [dict(r) for r in results] 如果我打印此变量,我有: [{'id': 1, 'type': '{"organization":"Dunder Mifflin","reported_at":"2015-04-21","created_at":"2015-04-22","inventory
reports
results = db.engine.execute("SELECT * FROM reports")
reports = [dict(r) for r in results]
如果我打印此变量,我有:
[{'id': 1, 'type': '{"organization":"Dunder Mifflin","reported_at":"2015-04-21","created_at":"2015-04-22","inventory":[{"name":"paper","price":"2.00"},{"name":"stapler","price":"5.00"}]}'}, {'id': 2, 'type': '{"organization":"MOM Corp.","reported_at":"3015-08-24","created_at":"3015-08-23","inventory":[{"name":"bending unit","price":"2000.00"},{"name":"stapling unit","price":"50.00"}]}'}, {'id': 4, 'type': '{"organization":"Flowers Inc.","reported_at":"2017-11-19","created_at":"2017-11-23","inventory":[{"name":"Flower pot","price":"2.00"},{"name":"Roses, 24","price":"50.00"}]}'}, {'id': 5, 'type': '{invalid_json'}]
我想在我的模板中呈现变量reports
,并对循环执行for
以遍历所有报告
@app.route('/allreports')
def allreports():
return render_template("allreports.html", reports=reports)
但是
因为它是一个列表,所以我不能执行for循环
例如,我无法打印每个报告的“组织”。
我怎样才能做到
如果我执行for循环,我只能打印ID和type,而不能打印type
{% for report in reports %}
{{report['id']}
{{report['type']}
{% endfor %}
如果我执行{{report['type']['organization']}
则不会打印任何内容。我想是因为嵌套的dict是一个字符串,而不是dict
'type': '{"organization":"Dunder Mifflin","reported_at":"2015-04-21","created_at":"2015-04-22","inventory":[{"name":"paper","price":"2.00"},{"name":"stapler","price":"5.00"}]}'}
看起来
type
的值是有效的JSON。一个快速的解决方案是用dict形式的解析JSON覆盖字符串值
import json
for r in reports:
r['type'] = json.loads(r['type'])
现在,您可以在模板内部执行
report['type']['organization']
。我尝试了:results=db.engine.execute(“SELECT*FROM reports”)用于结果中的r:r.type=json.loads(r.type)reports=[dict(r)用于结果中的r]
但是现在我得到了:AttributeError:'RowProxy'对象没有属性'type'-r.type=json.loads(r.type)
我认为问题还在于json应该用双引号括起来,而我在type
之后用单引号括起来:'type':{“organization”..…我修正了答案。引号应该可以,因为单个引号构成一个字符串,其内容是带双引号的有效json。您的答案很好,但迭代应该在报告
或结果
上。您能编辑它吗?