如何使用 Flask 从 JSON 文件中获取和显示特定值

How to get and show specific values from JSON file with Flask

我对如何获取 JSON 文件中的特定数据有疑问。我正在使用 Flask,我的目的是获取特定数据并显示它。例如,用 patternsresponses 获得 greetingstag。目前我只能显示我的所有信息 intents.json 但我需要特定数据。

我的档案intents.json

{
    "intents": [{
            "tag": "greetings",
            "patterns": ["hi", "hello","hola","hola!", "hello"],
            "responses": ["Que tal!", "hi there, how can i help you"],
            "context": [""]
        },
        {
            "tag": "goodbye",
            "patterns": ["bye", "Nos vemos!", "see you later"],
            "responses": ["have a nice time, "bye"],
            "context": [""]
        }
     ]
}

app.py 文件显示数据的函数:

@app.route("/showing-data")
def showing_data():
    with open('intents.json', 'r') as myfile:
        data = myfile.read()
    return render_template('showing.html', title="page", jsonfile=json.dumps(data))

最后,showing.html 文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="container"></div>


<script>
        const jsonfile = JSON.parse({{jsonfile|tojson}});
        console.log(jsonfile);
        document.querySelector(".container").innerHTML = JSON.stringify(jsonfile, null, 10);
      </script>
</body>
</html>

如果我没理解错的话,您想显示从 JSON 文件加载的条目并允许用户使用标签搜索单个条目。
您不必为此任务使用 javascript。
下面的示例将数据加载到字典中。然后根据搜索输入对其进行过滤。如果查询为空,则返回所有记录。
为了便于搜索,所有标签都被提取并显示在一个选择列表中。
所有显示的条目均按标签排序。

import json
from flask import (
    Flask,
    render_template,
    request
)

app = Flask(__name__)

@app.route('/')
def index():
    q = request.args.get('q')
    with open('intents.json') as f:
        data = json.load(f)
    data = data.get('intents', [])
    tags = [intent['tag'] for intent in data]
    if q:
        data = [intent for intent in data if q in intent['tag']]
    return render_template('index.html', **locals())
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Index</title>
  </head>
  <body>

    <form method="get">
      <label for="q">Search</label>
      <input name="q" id="q" value="{{q}}" list="intent-tags" autocomplete="off"/>
      <datalist id="intent-tags">
        {% for tag in tags | sort -%}
        <option value="{{tag}}" />
        {% endfor -%}
      </datalist>
      <input type="submit" value="Go">
    </form>

    <dl>
    {% for intent in data | sort(attribute='tag') -%}
    <dt>{{ intent.tag }}</dt>
    <dd>{{ intent.patterns | join(', ') }}</dd>
    <dd>{{ intent.responses | join(', ') }}</dd>
    {% endfor -%}
    </dl>
  </body>
</html>