Flask Jinja2-解析JSON [英] Flask Jinja2 - Parse JSON
问题描述
我正在尝试在Jinja2 HTML模板中显示一些JSON结果,但是它返回一个空页,或者在新行中返回JSON的每个字符,或者返回每个带有空格的字符.
I'm trying do display some JSON results in a Jinja2 HTML Template, but it returns either an empty page, or every character of the JSON on a new row, or every character with spacing.
我要发送给Jinja2模板的对象如下:
The object that I'm sending to Jinja2 Template looks like this:
[
{
"name": "John",
"lastname": "Smith",
"age": 22,
"likes": [
{"fruits":
["bananas", "oranges"]
},
{"sweets":
["chocolate"]
}
]
}
]
我将JSON对象发送到Jinja2模板:
To send the JSON object to the Jinja2 template I use:
render_template("report.html", items=items)
在Jinja2模板HTML上,如果我使用 {{items}}
,它将完整的对象显示为文本.如果我尝试获取 {{items ['name']}}
,它将不会在页面上显示任何内容,则页面将完全空白.
On the Jinja2 Template HTML if I use {{ items }}
it displays the full object as text.
If I'm trying to get the {{ items['name'] }}
it will not display anything on the page, the page will be completely empty.
我也尝试过
{% for x in items %}
{{ x }}
{% endfor %}
,它仅显示相同的文本",但以空格隔开: [{"n a m e":"J o h n" [...]
and it only displays the same "text" but with spacing:
[ { " n a m e " : "J o h n " [...]
在HTML文件中,我正在尝试执行以下操作:
In the HTML file, I'm trying to do something like:
<div id="name">{{ items['name'] }}</div>
如何显示要传递给Jinja2的JSON对象中的对象?
How can I display the objects within the JSON object I'm passing to Jinja2?
推荐答案
我想我已经讲完了.
我首先必须 json_dumps
对象,然后再 json.loads
新对象.
I had to json_dumps
the object at first, and then to json.loads
the new object.
r = json.dumps(json_onject)
loaded_r = json.loads(r)
return render_template("report.html", items=loaded_r)
现在我可以使用JSON对象中的任何值.
And now I can use any value from the JSON object.
这篇关于Flask Jinja2-解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!