Home > Software design >  How to get and show specific values from JSON file with Flask
How to get and show specific values from JSON file with Flask

Time:03-13

I've problem about how to get specific data on JSON file. I'm working with Flask and my intent to is get specific data and show it. For example, get tag of greetings with their patterns and responses. At this moment I just can show all information of my intents.json but I need specific data.

My file 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:

@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

<!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 ></div>


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

CodePudding user response:

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.
You don't have to use javascript for this task.
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>
  • Related