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

Issue

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.

Solution

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>

Answered By – Detlef

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published