Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
Proper way to pass/read CSV derived JSON with Flask/Javascript

So what I'm trying to do eventually is read a CSV on the backend using Python/Flask and display it as an HTML table using Javascript.

I've stripped things down to just trying to get console.log() to display the JSON values getting passed from my Python routine. Once I can retrieve my JSON values at will, building the table should be no issue.

Here's my code right now:

__init__.py

from flask import Flask, render_template
import json
import csv

app = Flask(__name__)
filePath = "/protec/test.csv"

@app.route("/") 
def index(): 
    tableData = get_table_data()
    return render_template("index.html", tableData=tableData)

def get_table_data():
    tableData = []
    with open(filePath, encoding='utf-8') as file:
        csvReader = csv.DictReader(file)

        for row in csvReader:
            tableData.append(row)

    with open(filePath, 'r', encoding='utf-8') as jsonf:
        tableString = json.dumps(tableData, indent=4)

    return tableString

if __name__ == "__main__": app.run()

script portion of index.html that (for now) triggers via onpageshow

<script>
    function build_table() {
        var parsedData = ' {{ tableData }} ';
        console.log(parsedData);
    }
</script>

my very simple test.csv file

first,last,age,hair
john,doe,29,brown
jane,doent,30,blond

From Python, I've tried returning both tableData and tableString. When I return tableString, I get an error when I inspect in the browser.

Uncaught SyntaxError: Invalid or unexpected token

When I return tableData, I get... something... in the console, but it's not really JSON and has some weird values that (I think) represent quotes.

[{&#39;first&#39;: &#39;john&#39;, &#39;last&#39;: &#39;doe&#39;, &#39;age&#39;: &#39;29&#39;, &#39;hair&#39;: &#39;brown&#39;}, {&#39;first&#39;: &#39;jane&#39;, &#39;last&#39;: &#39;doent&#39;, &#39;age&#39;: &#39;30&#39;, &#39;hair&#39;: &#39;blond&#39;}] 

I'm new to web development and frameworks and couldn't seem to find an example that was passing more than a single JSON record at a time. Any help is appreciated.

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

To achieve your goal you just need to pass your list tableData to the template.

from flask import Flask, render_template
import json
import csv

app = Flask(__name__)
filePath = '/protec/test.csv'

@app.route("/")
def index():
    tableData = get_table_data()
    return render_template('index.html', tableData=tableData)

def get_table_data():
    tableData = []
    with open(filePath, encoding='utf-8') as file:
        csvReader = csv.DictReader(file)
        tableData = [row for row in csvReader]
    return tableData

Within the template you can then use the jinja2 filter tojson to convert the data into a JSON-compliant format. Now you get an array of objects which you can process with JavaScript.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

    <script>
        (function build_table() {
            var data = {{ tableData | tojson }};
            console.log(data);
        })();
    </script>

  </body>
</html>
about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda