【问题标题】:Looping through JSON in a Selmer template在 Selmer 模板中循环 JSON
【发布时间】:2015-12-15 02:12:08
【问题描述】:

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

【问题讨论】:

    标签: clojure luminus selmer


    【解决方案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 %} 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-20
      • 1970-01-01
      • 1970-01-01
      • 2019-03-13
      • 2019-04-11
      相关资源
      最近更新 更多