Updated: January 23, 2023.
The data layer is the foundation upon which Google Tag Manager is largely built. It guarantees maximum flexibility, portability and ease of implementation.
In my other blog post,I explained how it works and how you can get the most out of it. However, not all aspects were addressed there. Since data can be saved using different structures, it must also be accessed differently. In today's blog post, I'll explain three ways you should extract data from the data layer.
While all three methods include a data layer variable that can be created in the Google Tag Manager container, your setup will be slightly different.
if you read myguide on GTM debugging and preview mode, you already know that the Data Layer tab is the most undervalued and utterly underutilized part of the GTM debug console, which is overlooked by novice and (mostly) intermediate users.
This tab shows the same message object that was sent to the data layer for the selected event and what the data layer looks like after the message transaction is complete.
In other words, you can see all the data currently available in the data layer and what values were available after each Google Tag Manager event. And the best: each data point (sent to the data layer) can be transformed into a variable in Google Tag Manager.
table of contents
– Hide index –
- before continuing
- #1. Access to first-level keys (also known as primitive values)
- #two. Extract data from child keys (also known as nested fields)
- #3. Extract data from array members
- Last words
In this blog post, you'll see three types of data in JavaScript: strings, objects, and arrays. However, if you want to go deeper and properly understand how they work in GTM, then subscribe to myIntermediate Google Tag Manager course.
#1. Access to first-level keys (also known as primitive values)
you are probably wonderingWhy did I call them "first level keys"?? I will explain it at the end of this chapter.
For my WordPress blog I am usingplug-in GTM4WP, which pushes some keys and values on every page load:
- Key:pagePostType, valor:mail
- Key:pagePostType2, valor:single post
- Key:category of page, valor:Google Tag Manager Tips
- Key:pagePostAuthor, valor:Julius Fedorovicius
See image below.
With the help of Google Tag Manager, I can easily convert each of these into data layer variables and reuse them in other tags.
Let's say you want to send a Google Analytics event when someone leaves a comment. With each event, you'll also want to submit the full name of the author of the article. That way, you'll see which authors generate the most reader engagement.
In this example, I won't go into detail on how to create a tag, I'll just demonstrate how to extract data from the data layer and convert it to a variable (within Google Tag Manager).
In Google Tag Manager account, you need to loginVariablesand create a new one with the following settings (dlvrepresentadata layer variable):
That is all! Save this variable, refresh the Preview and Debug (R&D) mode, and refresh the site you are working on. You should then see your newly created variable in theVariablesR&D Console Guide.
Oh, I almost forgot. You're probably still thinking, why did I call it "first level key"? Well, that's because those four keys don't have primary keys. Let me illustrate. Here is an example where the key is on the first level.
{pagePostAuthor: 'Julio Fedorovicius'}
And here is the second level key becausepagePostAuthoris descended fromattributeskey:
{attributes: {pagePostAuthor: 'Julius Fedorovicius'}}
In the next chapter, I'll explain how you can extract data from the data layer if the key isn't in the first level.
#two. Extract data from child keys (also known as nested fields)
Let's try to say this as non-technically as possible: when keys are descendants of other keys, they are called child keys (I found a lot of terms in this one to be honest, butchild keysounds more understandable to non-developers). In the following example, you can see thatattributesare on the first level, andpagePostAuthoris the 2nd
{attributes: {pagePostAuthor: 'Julius Fedorovicius'}}
To get its value, you need to slightly change a setting on a variable (within Google Tag Manager). Rather thanpagePostAuthor, you must enterattributes.pagePostAuthoras the data layer variable name.
And yespagePostAuthoralso had a child key? What would you do?
{atributos: {pagePostAuthor: 'Julius Fedorovicius': {someOtherKey: 'example'}}}
The answer is:
So it is. You must set the full path to that specific key:attributes.pagePostAuthor.someOtherKey, and so on... and so on... A dot must separate each level.
Accessing minor keys in the data layer is pretty standard. When someone asks me to give an example, I always talk about the AJAX listener, which helps track AJAX form submissions.
In my blog post,Google Tag Manager AJAX form trackingI explained how to use the AJAX listener (by Bounteous). It listens to all AJAX requests and sends its data to the data layer. Here is an example:
There are many nested keys. To extract data from the data layer, you will need to use dot notation in the data layer variable settings, for example,attributes.response.
#3. Extract data from array members
I was working with a developer on implementing Google Analytics eCommerce tracking. Following Google's guidelines, I asked a developer tosend data from successful requests to data layer. I was then able to get this event (and its data) with a GA4 event tag within Google Tag Manager.
It is essential that the developer follows the guidelines and sends the data using the structure as instructed by Google. Here is the official example from their knowledge base:
window.dataLayer = window.dataLayer || [];window.dataLayer.push({ event: 'purchase', e-commerce: { transaction_id: 'T_12345', affiliation: 'Google Merchandise Store', value: 25.42, tax: 4.90, shipping: 5 , 99, currency : 'USD' , coupon: 'SUMMER_SALE', items: [ { item_id: 'SKU_12345', item_name: 'Stan and Friends Tee', item_category: 'Clothing', price: 9.99, quantity: 1 } , { item_id: 'SKU_12346 ', item_name: 'women gray Google T-shirt', item_category: 'Clothing', price: 20.99, quantity: 1 }] } });
"You know that?" I asked myself: "This is very useful information." I'd also like to send this order data to other marketing tools I'm using (eg Facebook Pixel). I was interested above allprice, name, youamount.
So I tried method #2 (from this blog post) and it failed. used to beecommerce.price, ecommerce.item_name, etc., but my newly created data layer variables always returned undefined. So what's wrong?
Do you notice anything suspicious? In my GA4 ecommerce example (taken from Google knowledge base) there are 2chaves element_name, 2price keys, etc. So how the hell does Google Tag Manager know what value I'm interested in? The first or the second? And what would happen if a user bought 5 products?
What we are dealing with here is calledarrangements. Hee-commerce itemsYou have an array containing two products with the same key collections:item_id, item_name, item_category, precio, cantidad.
In Javascript, if you want to get the price value of the first product, you should useecommerce.items[0].price(index starts at 0), but the Google Tag Manager data layer variable doesn't support square brackets in this context, so you'll need to use dot notation, like this:e-commerce.items.0.price.
In Google Tag Manager, your data layer variable should look like this:
If there were five products in the array and you wanted to access the price of the fifth product, the data layer variable name would bee-commerce.items.4.price. Remember, the index here starts at zero, so the first product is not 1, but 0.
Final words on extracting data from the data layer
Since data can be saved using different structures, it must also be accessed differently.
Now you know how to extract data from the data layer in 3 different ways. Although they all use the same data layer variable, their names are different depending on the data structure: arrays, nested keys, or unique keys (first level).