[英]print JSON string converted from python object using flask
我有这个 flask 服务器正在运行,我制作了这个 html 文件,该文件有一个脚本,当我单击按钮时,它将返回一个 JSON 字符串。 然而,它一直给我 undefined 。 我有这个 app.py 代码,它给了我一个 python 字典,我将它转换为 JSON
@app.route('/')
def helloworld():
#result = jsonify(student)
html_item = json.dumps(Marks, indent=2, separators=(', ', ': '))
return render_template('test1.html',data = html_item)
在此之后 test1.html 我有一个脚本
<!DOCTYPE html>
<html>
<head>
<title>
JavaScript | Print content of object
</title>
</head>
<body style = "text-align:center;" id = "body">
<h1 style = "color:rgb(0, 2, 128);" >
{{data}}
</h1>
<p>
Print JavaScript Object.
</p>
<button onclick = "gfg_Run()">
print object
</button>
<p id = "GFG_DOWN" style
= "color:rgb(0, 2, 128); font-size: 20px; font-weight: bold;">
</p>
<script>
var el_down = document.getElementById("GFG_DOWN");
var GFG_object = {
prop_1: 'val_11',
prop_2: 'val_12',
prop_3: 'val_13'
};
function gfg_Run(data) {
el_down.innerHTML = data;
//el_down.innerHTML = JSON.stringify(GFG_object);
}
</script>
</body>
</html>
我已经测试过它可以通过我注释掉的行打印出一个js object。 我应该如何打印出 JSON 字符串,在我的情况下data
正确?
我假设您应该知道如何检索 json 数据?!
如果没有,则访问: https://www.programiz.com/python-programming/json
既然您知道如何检索以 json 格式存储的数据,您应该将值直接放入 inner_html 中,例如:
el_down.innerhtml = data['val']
或者,您的 json 结构可能是......
我认为您访问 json 数据的方式不正确。 请在您尝试此解决方案后告诉我。
您没有在 html 模板中呈现 json 字符串
仅仅拥有单词data
不会从您的 python 脚本中获取data
变量并将其替换为您的 json。 您需要将其括在花括号{{}}
中
//incorrect
myobject = data;
//correct
myobject = {{ data|safe }};
所以为了让你的例子工作你可以做
var GFG_object = {{data|safe}};
//took out the "data" from the parameter list
//since you aren't passing anything to gfg_Run()
function gfg_Run() {
//prints your object as a json string
el_down.innerHTML = JSON.stringify(GFG_object);
}
//if you are wanting print some property of your object
function gfg_Run() {
el_down.innerHTML = GFG_object["val"];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.