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.

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
    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">


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

<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=""></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
            contentType: "application/json",
            data: JSON.stringify(s)});




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!

5 thoughts on “How to Pass a Javascript Variable to Python using JSON

  • July 20, 2022 at 7:36 pm

    I usually never leave feedback, but thank you so much for this, works like a charm, it is perfect.

    • July 25, 2022 at 10:43 pm

      Thank you for visiting the website and YouTube channel. Your comment is really appreciated.

      Data Analytics Ireland

    • August 20, 2022 at 2:50 pm

      Thank you so much for your kind comment and feedback it is really appreciated.

      Data Analytics Ireland

  • April 21, 2022 at 10:25 am

    Extremely helpful Post.

    Being highly allergic to JavaScript there was , at least for me , a lot more than met the eyes. The flask route (@app.route(‘/test’, methods=[‘POST’]) is not the usual html rendering but a cunning method triggered by the JavaScript function to actually operate a variable transfer to python. Bravo.
    From here the variable can either be made global for further python handling or simply stored into a Redis db.

    Thank you very much

    • May 2, 2022 at 8:25 pm


      Thank you so much for taking the time to read the posting, and comment. I have another post coming soon about how to validate the data entered using python, but the data is entered in a HTML input box and passed to python via JSON/ajax.

      Data Analytics Ireland


Leave a Reply

Your email address will not be published.