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!