简体   繁体   English

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

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

I've problem about how to get specific data on JSON file.我有关于如何获取 JSON 文件的特定数据的问题。 I'm working with Flask and my intent to is get specific data and show it.我正在使用 Flask,我的目的是获取特定数据并显示它。 For example, get tag of greetings with their patterns and responses .例如,获取带有patternsresponsesgreetings tag At this moment I just can show all information of my intents.json but I need specific data.此时我只能显示我的意图的所有信息intents.json但我需要具体数据。

My file 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": [""]
        }
     ]
}

Function of app.py file to show data: Function 的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))

And finally, showing.html file最后, 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>

If I understood you correctly, you want to display the entries that were loaded from a JSON file and allow the user to search for individual entries using the tag.如果我理解正确的话,您想要显示从 JSON 文件加载的条目,并允许用户使用标签搜索单个条目。
You don't have to use javascript for this task.您不必为此任务使用 javascript。
The example below loads the data into a dict.下面的示例将数据加载到字典中。 It is then filtered based on the search input.然后根据搜索输入对其进行过滤。 If the query is empty, all records are returned.如果查询为空,则返回所有记录。
For easier searching, all tags are extracted and displayed within a selection list.为了便于搜索,所有标签都被提取并显示在一个选择列表中。
All displayed entries are sorted by tag.所有显示的条目都按标签排序。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM