Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

316
Views
Cómo obtener y mostrar valores específicos del archivo JSON con Flask

Tengo un problema sobre cómo obtener datos específicos en el archivo JSON. Estoy trabajando con Flask y mi intención es obtener datos específicos y mostrarlos. Por ejemplo, obtener tag de greetings con sus patterns y responses . En este momento solo puedo mostrar toda la información de mi intents.json pero necesito datos específicos.

Mi archivo 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": [""] } ] }

Función del archivo app.py para mostrar datos:

 @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))

Y finalmente, showing.html el archivo.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>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Si lo entendí correctamente, desea mostrar las entradas que se cargaron desde un archivo JSON y permitir que el usuario busque entradas individuales usando la etiqueta.
No tienes que usar javascript para esta tarea.
El siguiente ejemplo carga los datos en un dict. Luego se filtra en función de la entrada de búsqueda. Si la consulta está vacía, se devuelven todos los registros.
Para facilitar la búsqueda, todas las etiquetas se extraen y se muestran en una lista de selección.
Todas las entradas mostradas están ordenadas por etiqueta.

 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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!