I have a div in my webpage that contains some valid JSON string. I get its value using the text() function in jQuery like this:
$("div.selector").text();
The JSON string contains some new lines and tabs. It is perfectly valid and matches the formatting expected by Google Tag Manager Enhanced eCommerce (https://developers.google.com/tag-manager/enhanced-ecommerce).
The problem I am facing is that using the following prevents the event from being registered
dataLayer.push($("div.selector").text());
while pasting the JSON inside push() manually registers the event properly:
dataLayer.push(VALID JSON);
Using
dataLayer.push($("div.selector").text());
pushes a text string in dataLayer that looks like this
{\n\t\t\"event\": \"someEvent\",\n\t\t\"eventCategory\": \"Order Update\"
How can I push valid JSON that has been extracted using text()?
Use JSON.parse()
eg: dataLayer.push(JSON.parse($("div.selector").text()));