我正在制作简单的问答游戏,并希望将问题存储在JSON文件中,如下所示:
{"questions":
[
{
"question":"2+2 ?",
"answer_A":1,
"answer_B":2,
"answer_C":3,
"answer_D":4,
"correct_answer":4
},
{
"question":"2+3?",
"answer_A":1,
"answer_B":2,
"answer_C":3,
"answer_D":5,
"correct_answer":5
}
] }
这是从文件加载它的代码:
defn json-page []
(layout/render
"json.html" {:file (parse-string (slurp "path/to/file"))}))
parse-string返回一个字符串,所以我不能遍历它来显示每个元素。我怎样才能做到这一点?我知道语法({% for question in file %})
,但我不知道如何访问嵌套元素。
答案 0 :(得分:1)
感谢Reddit的回答:
(defn json-page []
(layout/render
"json.html" {:file (parse-string (slurp "path/to/file") true)}))
答案是添加true作为parse-string
的参数来关联json地图。在此之后我可以循环json:
{% for question in file.questions %}
<p>{{ question.question }}.</p>
{{ question.answer_A}}
{{ question.answer_B}}
{{ question.answer_C}}
{{ question.answer_D}}
{% endfor %}