Accessing The GTM Ecommerce Data Layer With PyScript For Browser-Based Web Analytics
Bj?rn Thomsen
Marketing Lead at meshcloud.io | Accelerating B2B Market Growth | Professional in Performance Marketing & Web Analytics
PyScript is a framework that enables users to develop sophisticated Python applications in the browser using HTML's interface and harnessing the capabilities of Pyodide, WebAssembly (WASM), and contemporary web technologies. This allows functions such as data cleaning, analysis, visualization, and even local execution of machine learning in the user's own browser.
While my last article focused on the possibilities of analyzing and visualizing Google Ads data in PyScript, today's topic revolves around web tracking and analyzing DataLayer information.
In essence, I'll illustrate how to seamlessly transfer a JavaScript DataLayer object containing Google ecommerce data to PyScript, ensuring its readability for subsequent analyses. Let's get started.
Step 1: Preparing The <head> Section
Firstly, we need to integrate PyScript in the <head> section to utilize it later. To do this, we refer to an external source; alternatively, we could store the code in our own cloud space.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Examples: Accesing the dataLayer with pyscript</title>
<link
rel="stylesheet"
/>
<link rel="stylesheet" href="./assets/css/examples.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
</head>
Step 2: Pushing a DataLayer
In the next step, we need a DataLayer that Google Tag Manager (GTM) can interpret. We'll use the Advanced Ecommerce Layer provided by Google on its website and modify a bit.
Then, we insert this JavaScript in the upper section of the <body> area of our html and parse ist.
<script>
//let's start with creating a datalayer with typical ecommerce data
//we follow Google's example here with a few modifications: https://developers.google.com/analytics/devguides/collection/ua/gtm/enhanced-ecommerce
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'ecommerce': {
'currencyCode': 'EUR',
'impressions': [
{
'name': 'Triblend Android T-Shirt',
'id': '12345',
'price': '15.25',
'brand': 'Google',
'category': 'Apparel',
'variant': 'Gray',
'list': 'Search Results',
'position': 1
},
{
'name': 'Donut Friday Scented T-Shirt',
'id': '67890',
'price': '33.75',
'brand': 'Google',
'category': 'Apparel',
'variant': 'Black',
'list': 'Search Results',
'position': 2
}]
}
});
console.log(dataLayer);
</script>
Step 3: Inspecting The DataLayer in The Console.
To verify whether the DataLayer.push has been executed correctly, we can check in the console of our web browser. Here, we access the DataLayer using the command.
Step 4: Providing a Global String Object.
The main challenge is that PyScript cannot directly access HTML or JavaScript objects. We need to build a bridge for this. First and foremost, a global object must be created, which PyScript can interpret later. After some experimentation, I've chosen to convert the JSON data structure into a string using JSON.stringify.
pyscriptResult = JSON.stringify(dataLayer);
Step 5: Ensuring That PyScript Can Display Messages
Now, we create a <div> element in the <body> section and assign it an ID for the subsequent output of our PyScript.
<div id="ausgabe"></div>
Step 6: Data Wrangling & Analysis in PyScript
Now comes the truly exciting part.?? We create a PyScript and import our global JavaScript variable "pyscriptResult" using "from js". To process the data contained herein, which is flat as a string, we need to convert it into a format readable by Python. I've opted for a classic dictionary. Before accomplishing this with json.loads, we need to clean up the character set. There's an "[" at the beginning and a "]" at the end of the character set. Accordingly, we read the string from [1:-1:0]. Also, as a precaution, let's output the data type.
Now we can work with the E-commerce data from the DataLayer. In our example, we keep it simple, extract the prices of the two products, and display them along with the currency code.
To demonstrate that we can manipulate the data, let's simply sum up the total value of the goods and also display it on the web interface. The entire code looks like this...
<py-script output="ausgabe">
from js import pyscriptResult
import json
obj = json.loads(pyscriptResult[1:-1:1])
print(type(obj))
currency=str(obj['ecommerce']['currencyCode'])
price_item_1 = float(obj['ecommerce']['impressions'][0]['price'])
price_item_2 = float(obj['ecommerce']['impressions'][1]['price'])
total = price_item_1 + price_item_2
print('Item number 1:')
print(str(price_item_1) + ' ' + currency)
print('Item number 2:')
print(str(price_item_2) + ' ' + currency)
print('Sum: '+ str(total))
</py-script>
......and in the browser, it looks like this...
Indeed, it doesn't take much imagination to see the potential applications of PyScript with GTM E-commerce data. From simple min-max calculations to calculating average order value or providing real-time recommendations for similar products and product categories:there are numerous possibilities for leveraging the power of PyScript in this context. The flexibility and functionality it brings to web-based data processing open the door to a variety of data-driven enhancements and insights.
Furthermore, PyScript could also be utilized by the web analysts themselves to read the DataLayer and validate new functions. This hands-on approach could enable web analysts to directly interact with and test ecommerce data.