Create a HTML Table From Python Using Javascript

Estimated reading time: 5 minutes

So you are using Python and you have data stored in a data frame? You would like to present that on a webpage HTML table, but unsure how to achieve this. Well, read on to see two different methods that will help you.

Pass the data to Javascript which then passes to the HTML the data needed to create the table

In both methods, we are using Python Flask which has an app.py file and HTML files created to present the outcomes.

Step 1 – Read the data and create the data frame

For those familiar with Python Flask, we create the imports that allow us to create the webpage interface to present the data.

Then we create a list called data, which stored the information we need. After this, we create the data frame “df”.

Finally, we create a JSON file,and do some data cleansing.

from flask import Flask, render_template, json
import pandas as pd


app = Flask(__name__)

data = [['Joe','Dublin','100'],['Francois','Paris','100'],['Michael','Liverpool','100']]
df = pd.DataFrame(data, columns = ['Name', 'City','Age'])


json_output = df.to_json()
json_output = json.loads(json_output.replace("\'", '"')) # Removes back slash from JSON generated

Step 2 – Create the output HTML files

Method 1 – Here all this is doing is creating the function to create the webpage “index.html”. Note that name_json=json_output captures the data from step one, and this is what is passed over to the HTML page as a JSON.

In method 2 – We are using to_html which Renders a DataFrame as an HTML table, pure and simple.

As can be seen, it stores the data onto an HTML page that is stored in the templates folder.

#Method 1
@app.route('/')
def index():

    return render_template('index.html', name_json=json_output)

#This is  the start of method 2#
html = df.to_html()
#write html to file
im2_file = open("templates/index_method2.html", "w")
im2_file.write(html)
im2_file.close()

@app.route('/index_method2')
def index_method2():
    return render_template('index_method2.html')


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

Step 3 – Create the HTML tables through javascript

So steps 1 and 2 were getting the data ready so it can be viewed on the web pages, so how are they built?

So let’s walk down through the code, note that a good bit of this is the HTML that is used to present the data on the page.

The first thing to notice is the <style></style> tags. this is for method 1 and applies the boxes around the output.

<pre id=”json”></pre> – This line shows the JSON data as follows:

JSON Output

In the below few lines this is the HTML that creates the table to store the data from method 1:

<table id="json_table"> ===> Method 1 table
    <tr>
        <td> Name</td>
        <td> City</td>
        <td> Age</td>
  </tr>
</table>

The next section has the Javascript that will populate both for method 1 and method 2, I will go through it now:

So the first line is creating a variable that references the method 1 table, and where the JSON data will be loaded to.

The second line is converting the JSON into a format that can be read and shown as the “JSON” screenshot above.

In Line 3 & 4, all we are doing here is creating a variable to store the output of the loop that follows in the subsequent lines.

The final set of lines in the script except for the very last line ( which relates to Method 2) catch the data that is captured as part of the loop and feed it to the table that appears on index.html, as follows:

HTML table created from a python data frame using Javascript.

The final line:

window.open(‘http://127.0.0.1:5000/index_method2’, ‘_blank’);

In the Javascript section, this relates to Method 2 and takes the data directly from the app.py file and outputs it to http://127.0.0.1:5000/index_method2.html

This is a very quick and easy way to create the HTML table, and as can be seen, involves less coding than method 1.

<script>
    var selectvalue = document.getElementById("json_table"), test={{ name_json | tojson }}; ===> First line
    document.getElementById("json").textContent = JSON.stringify(test, undefined, 2); ===> Second line

    const keys = Object.keys(test); ===> Line 3
    for (let i = -1; i < keys.length-1; i) ===> Line 4

    {
        const key = keys[i++];

        console.log(key, test[key]);

        a = JSON.stringify(test["Name"][i])
        b = JSON.stringify(test["City"][i])
        c = JSON.stringify(test["Age"][i])
        const tbl = document.getElementById("json_table");
        const row = tbl.insertRow();
        const cell1 = row.insertCell();
        const cell2 = row.insertCell();
        const cell3 = row.insertCell();
        cell1.innerHTML = a;
        cell2.innerHTML = b;
        cell3.innerHTML = c;

    }

    window.open('http://127.0.0.1:5000/index_method2', '_blank');

  </script>

The Full HTML code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Document</title>
</head>
<style>
table, td {
  border: 1px solid;
}
</style>
<body>
<pre id="json"></pre>
<div>Method 1 pass the data via JSON to Javascript </div>
<table id="json_table">
    <tr>
        <td> Name</td>
        <td> City</td>
        <td> Age</td>
  </tr>
</table>

  <script>
    var selectvalue = document.getElementById("json_table"), test={{ name_json | tojson }};
    document.getElementById("json").textContent = JSON.stringify(test, undefined, 2);

    const keys = Object.keys(test);
    for (let i = -1; i < keys.length-1; i)

    {
        const key = keys[i++];

        console.log(key, test[key]);

        a = JSON.stringify(test["Name"][i])
        b = JSON.stringify(test["City"][i])
        c = JSON.stringify(test["Age"][i])
        const tbl = document.getElementById("json_table");
        const row = tbl.insertRow();
        const cell1 = row.insertCell();
        const cell2 = row.insertCell();
        const cell3 = row.insertCell();
        cell1.innerHTML = a;
        cell2.innerHTML = b;
        cell3.innerHTML = c;

    }

    window.open('http://127.0.0.1:5000/index_method2', '_blank');

  </script>


</body>
</html>

#how to create a html table from a python dataframe using javascript

The Final output

Method 1
Method 2

How to Pass a Javascript Variable to Python using JSON

Estimated reading time: 4 minutes

So you have an application or website that is capturing data using javascript, and you want to pass this to Python, so you can process it further.

Here using Flask, Python’s package for web development, we will show you how to achieve this, and also explain the JSON output.

Where could this be useful?

(A) You want to pass data to a Python program to run a Machine Learning program you have written.

(B) You want to use Pythons functionality to add the data to a dashboard in real-time.

(C) Another use could be that you are in real-time processing requests on a website, but also want to use Python’s functionality to capture metrics on the data.

So how do we achieve this?

Step 1 – In Python create a Flask application

When you create a new Python file, the first step is to create add your import statements to the top of the file:

import json

from flask import request

from flask import Flask, render_template

app = Flask(__name__)

As can be seen from the above, we bring in the flask package. This is now starting the process of creating a web development site.

Step 2 – Create the web route for telling the programme what the HTML template is called.

@app.route('/')
def index():
return render_template('index.html')

Step 3 – Create the logic that will receive the data from the JSON on the website.

@app.route('/test', methods=['POST'])
def test():
    output = request.get_json()
    print(output) # This is the output that was stored in the JSON within the browser
    print(type(output))
    result = json.loads(output) #this converts the json output to a python dictionary
    print(result) # Printing the new dictionary
    print(type(result))#this shows the json converted as a python dictionary
    return result

In the above we will explain the logic:

/test ===> this is what the page further on the logic will look to send the data entered on the website to.

methods=[‘POST’] ===> This is what it is looking out for when the JSON is been sent.

As can be seen in the function the rest of the code just retrieves the data and processes it.

Step 4 – Create the HTML file that will capture input and process the data to JSON.

So the main part of this program is loading the HTML file, entering the data onto the page and then processing it with javascript and AJAX.

The page looks like this:

The code behind this is as follows:

<html lang="en">

<head>

    <title>Data Analytics Ireland</title></head>
<body>

<P>Post some values to a json file</P>


<label for="fname">First name:</label> <input type="text" id="fname" name="fname">
<label for="lname">Last name:</label><input type="text" id="lname" name="lname">
<button type="submit" onclick='myfunction();'>Click Here to see your data</button>


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
    function myfunction() {

        const firstname = document.getElementById("fname").value;
        const lastname = document.getElementById("lname").value;


        const dict_values = {firstname, lastname} //Pass the javascript variables to a dictionary.
        const s = JSON.stringify(dict_values); // Stringify converts a JavaScript object or value to a JSON string
        console.log(s); // Prints the variables to console window, which are in the JSON format
        window.alert(s)
        $.ajax({
            url:"/test",
            type:"POST",
            contentType: "application/json",
            data: JSON.stringify(s)});

}

</script>



</body>
</html>

This block of code is HTML and runs as follows:

There are two input text boxes that take the data entered.

There is a button that when clicked, runs the function onclick=’myfunction();’

Within this function, the const firstname and const lastname capture the values entered into the boxes using the javascript document.getElementById

We then create a dictionary with those values.

Next, we create a variable that takes the dictionary and converts it into the JSON format.

The section starting with ” $.ajax“, creates the JSON and readies it to be passed to “/test” identified in step3.

STEP 5 – Where does this leave us?

At this point, if the program is run and the data has been entered, and the button is clicked, the data has been captured by the javascript, passed into the dictionary and converted to JSON format.

So what does this all look like when completed?

Data entered:

Printed output:

The data first comes as JSON str and is then converted to a Python dictionary.

After this, you can then start manipulating the data in Python!