我對如何獲取 JSON 檔案的特定資料有疑問。我正在使用 Flask,我的意圖是獲取特定資料并顯示它。例如,tag與greetings他們的patternsand相處responses。此時我只能顯示我的所有資訊,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>
uj5u.com熱心網友回復:
如果我理解正確,您希望顯示從 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/443962.html
標籤:javascript Python html json 烧瓶
