Flask:如何将python字典转换为JSON?
我有一个Flask应用程序,其中我将字典作为参数传递给正在呈现的HTML页面:Flask:如何将python字典转换为JSON?,python,json,flask,Python,Json,Flask,我有一个Flask应用程序,其中我将字典作为参数传递给正在呈现的HTML页面: @app.route('/cyto') def testfn(): nodes={ "nodes": [ { "data": {"id": "a", "label": "Gene1"} },
@app.route('/cyto')
def testfn():
nodes={
"nodes": [
{
"data": {"id": "a", "label": "Gene1"}
},
{
"data": {"id": "b", "label": "Gene2"}
},
{
"data": {"id": "c", "label": "Gene3"}
},
{
"data": {"id": "d", "label": "Gene4"}
},
{
"data": {"id": "e", "label": "Gene5"}
},
{
"data": {"id": "f", "label": "Gene6"}
}
],
"edges": [
{
"data": {
"id": "ab",
"source": "a",
"target": "b"
}
},
{
"data": {
"id": "cd",
"source": "c",
"target": "d"
}
},
{
"data": {
"id": "ef",
"source": "e",
"target": "f"
}
},
{
"data": {
"id": "ac",
"source": "a",
"target": "d"
}
},
{
"data": {
"id": "be",
"source": "b",
"target": "e"
}
}]
}
nodes=json.dumps(nodes, ensure_ascii=False)
return render_template("cytoscape_result.html", nodes=nodes)
这是cytoscape_result.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.18.2/cytoscape.min.js"></script>
<title>Result</title>
</head>
<body>
<script>
JSON.parse({{ nodes }})
</script>
</body>
</html>
我认为问题在于JSON.parse将字典条目周围的双引号解释为ascii代码,而不是实际的双引号。如何让JSON.parse将它们解释为双引号?我尝试在json.dumps中设置sure_ascii=False,但仍然出现错误。将dict传递给jinja模板,并使用过滤器将其转换为json
@app.route('/cyto')
def testfn():
nodes={
"nodes": [
# ...
],
"edges": [
# ...
]
}
return render_template('cytoscape_result.html', nodes=nodes)
const data={{nodes|tojson}};
控制台日志(数据);
@app.route('/cyto')
def testfn():
nodes={
"nodes": [
# ...
],
"edges": [
# ...
]
}
return render_template('cytoscape_result.html', nodes=nodes)
<script>
const data = {{ nodes | tojson }};
console.log(data);
</script>