给出正确答案后,如何遍历JSON数据问题?

时间:2018-09-24 12:59:52

标签: python json flask

我正在使用Python和Flask构建一个简单的谜语问答游戏。我的问题和答案存储在JSON文件中。

[
  {
    "name": "riddle_0",
    "description": "The more you take, the more you leave behind, what am i?",
    "answer": "footsteps"
  },
  {
    "name": "riddle_1",
    "description": "what has a head, a tail, is brown but has no legs?",
    "answer": "penny"
  },
  {
    "name": "riddle_2",
    "description": "what has many keys, but can't even open a single door?",
    "answer": "piano"
  }

我通过h1模板中的Game.html提出了问题。

<div class="row">
          <div class="col-xl-9 mx-auto">
            <h1 class="mb-5">{{ username }}</h1>
            <h1 class="mb-5">{{ company_data[0]["description"] }}</h1>
          </div>
          <div class="col-md-10 col-lg-8 col-xl-7 mx-auto">
            <form method="POST" class="form-inline">
                        <input type="text" class="form-control" placeholder="answer" name="message" id="message" autofocus>
                        <input type="hidden" name="riddle_index" id="riddle_index" value={{riddle_index}}>
                        <button class="btn btn-danger">Submit Answer</button>

通过路线访问

@app.route('/game', methods=["GET", "POST"])
def game_questions():
    data = []
    with open("data/company.json", "r") as json_data:
        data = json.load(json_data)
        return render_template("game.html", page_title="riddle_me_this", company_data=data)

如何正确构造for循环,以便在给出正确答案后迭代到下一个问题?

3 个答案:

答案 0 :(得分:0)

您可以json遍历json(在这种情况下为字典列表)并检查答案是否正确。如果答案是错误的,那就打破循环。例子

import json
for i in json.loads(your_json_string):
    print('Your Question is: '+i['description'])
    #take answer
    # if ans == i['answer'] #continue for loop
    # else
    # break

如果要保留谜题编号,请首先对列表进行排序。例子

a='''[
  {
    "name": "riddle_0",
    "description": "The more you take, the more you leave behind, what am i?",
    "answer": "footsteps"
  },
  {
    "name": "riddle_3",
    "description": "what has a head, a tail, is brown but has no legs?",
    "answer": "penny"
  },
  {
    "name": "riddle_2",
    "description": "what has many keys, but can't even open a single door?",
    "answer": "piano"
  }]
  '''
newlist = sorted(json.loads(a), key=lambda k: k['name']) # riddle_0,riddle_2,riddle_3
for i in newlist:
    print('Your Question is: '+i['description'])
    print('Your riddle '+i['name'])
    #take answer
    # if ans == i['answer'] #continue for loop
    # else
    # break

答案 1 :(得分:0)

这应该使您接近。我还捕获了谜语索引,因此您真的不需要继续遍历整个列表以查找匹配项。

from flask import render_template, request

@app.route('/game', methods=["GET", "POST"])
def game_questions():

    req = request.form.to_dict()
    user_answer = req.get('answer')

    with open("data/company.json", "r") as json_data:
        data = json.load(json_data)

    questions = [
      {
        "name": "riddle_0",
        "description": "The more you take, the more you leave behind, what am i?",
        "answer": "footsteps"
      },
      {
        "name": "riddle_1",
        "description": "what has a head, a tail, is brown but has no legs?",
        "answer": "penny"
      },
      {
        "name": "riddle_2",
        "description": "what has many keys, but can't even open a single door?",
        "answer": "piano"
      }]

    new_question = None        

    for i, question in enumerate(questions):
        if question['answer'] == user_answer:
            try:
                new_question = questions[i + 1]['description']
                question_index = int(questions[i + 1]['name'].split('_')[1])

            except IndexError:
                new_question = 'No more questions left'
                question_index = None
            break

    context = {'question': new_question, 'riddle_index': question_index}

    return render_template("game.html", page_title="riddle_me_this", 
                           company_data=data, context=context)

答案 2 :(得分:0)

我也可以尝试一下,即使已经有了足够好的答案,我也将发布它只是为了展示稍微不同的方法。

from flask import Flask, render_template_string, request
import json

with open("riddle.json", "r") as json_data:
    riddles = json.load(json_data)

app = Flask(__name__)

TEMPLATE_STRING = """
{{riddle['description']}}<br>
<form method="POST" class="form-inline">
    <input type="text" class="form-control" placeholder="answer" name="answer" id="message" autofocus>
    <input type="hidden" name="riddle_id" value="{{riddle_index}}">
    <button class="btn btn-danger">Submit Answer</button>
</form>
"""


@app.route('/game', methods=["GET", "POST"])
def game_questions():
    if request.method == 'GET':
        riddle_index = 0
    else:
        riddle_index = int(request.form['riddle_id'])
        if riddles[riddle_index]['answer'] == request.form['answer']:
            riddle_index += 1
            if riddle_index >= len(riddles):
                riddle_index = 0
    return render_template_string(TEMPLATE_STRING, riddle_index=riddle_index, riddle=riddles[riddle_index])

如果是获取请求,则发布第一个谜语;如果是发布请求且答案正确,则发布下一个谜语;如果是发布请求且答案错误,则再次发布相同的问题。如果所有谜语均已回答,它将重置谜题索引,因此您可以从头开始。