1

我正在制作简单的问答游戏,并希望将问题存储在 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 %}),但我不知道如何访问嵌套元素。

4

1 回答 1

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 %} 
于 2015-08-31T19:37:22.300 回答