[英]How do I pass my JSON string using Flask?
我创建了一个 JSON 字符串。 它看起来像这样:
{
"version": 1,
"type": "exercise",
"Exercises": {
"Exercises": [
{
"Overhead Press": [
{
"id": 1,
"interval": 10,
"resistance": 55,
"set_number": 1,
"workout_id": 2,
"workout_date": "2022-01-03T06:00",
"exercise_id": 1,
"exercise_name": "Overhead Press"
}
]
}
]
}
}
我使用json.dumps
创建它,如下所示: json_exercise_col = json.dumps(exercise_col, default=default, indent=1)
我认为我的json
字符串很好。 我可能是错的,所以我把它包括在内是为了让第二双眼睛盯着它。
我这样传递它:
return render_template("graph.html", graph_exercises=json_exercise_col, dropdown_menu=unique_exercise_names)
现在我要做的就是将它打印到我的console.log
。 我用这个: console.log({{graph_exercises}})
我收到此错误: Uncaught SyntaxError: "" string literal contains an unescaped line break
我已经尝试过解析 JSON 字符串的解释: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
当我做他们的简单示例时,它起作用了。
const g = '{"result":true, "count":42}';
const l = JSON.parse(g)
console.log(l);
但是当我尝试使用 Flask 传递我的字符串时,它没有。
const f = JSON.parse('{{graph_exercises}}')
console.log(f)
我在这里错过了什么? 因为我要通过 Flask 传递它,所以我需要做些什么特别的事情吗? 我只是错误地使用JSON.parse()
吗?
来源为HTML/JS:
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const g = '{"result":true, "count":42}';
const l = JSON.parse(g)
console.log(l);
const f = JSON.parse('{
"version": 1,
"type": "exercise",
"Exercises": {
"Exercises": [
{
"Overhead Press": [
{
"id": 1,
"interval": 10,
"resistance": 55,
"set_number": 1,
"workout_id": 2,
"workout_date": "2022-01-03T06:00",
"exercise_id": 1,
"exercise_name": "Overhead Press"
}
]
}
]
}
}')
让我们以你的第一个例子为例
const g = '{"result":true, "count":42}';
const l = JSON.parse(g)
console.log(l);
g
变量是可以解析的 object。 现在,如果您查看MDN 文档中的示例,您可以看到JSON.parse
是这样使用的:
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
在您的示例中,您没有传递任何 JSON 看起来您只是传递了一个包含在{{... }}
中的字符串
您可以将 JSON 导出到一个变量并将其传递。 所以像下面这样:
const someJson = graph_exercises
const parsedJson = JSON.parse(someJson)
但这里有几件事......
你说你正在将 JSON 导入到你的模板中,如下所示:
render_template("graph.html", graph_exercises=json_exercise_col, dropdown_menu=unique_exercise_names)
在graph.html
中,您可以使用 Jinja 访问graph_exercises
中的 graph_exercises。 所以你可以使用 Jinja 来遍历你的 JSON。就像......
<div>
{% for graph in graph_exercises | safe %}
<span id="exercise">{{graph.type}}</span>
{% endfor %}
</div>
作为一个非常基本的例子。 您可以在此处找到有关 Jinja 的更多信息:
https://jinja.palletsprojects.com/en/3.1.x/
https://www.reddit.com/r/flask/comments/itdtix/flask_json_parsing_and_structure_with_jinja_for/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.