1

I’m trying to automate some sanity checks for my GTM account to see that every event/object stays the same after website releases. Therefore I want to create/use some kind of JSON validator in javascript that can be used directly in the browser.

Is there any way to validate a JSON object in the browser? I’m working on a solution to scrape the dataLayer objects directly in the browser then check if the objects contain the right data. I have found a lot of different “JSON validators” in GitHub and such but none that supports to check the JSON objects in the console in browser.

For now I don’t think it’s needed to check whole JSON schema instead every object separately.

I have written some code to check


var dataLayerList = dataLayer;
var dataLayerEventName;
for(var i = 0; i < datalayerList.length; i++){
    var dataLayerObj = datalayerList[i];
    if(dataLayerObj.event){
        dataLayerEventName = dataLayerObj.event;
        switch(dataLayerEventName){
            case 'foo':
                foo(dataLayerObj);
                break;
            case 'bar':
                bar(dataLayerObj);
                break;
        }
    }
}


function foo(dataLayerObj){
    //check if dataLayerObj contains the same keys and value types as predefined JSON object
}

function bar(dataLayerObj){
    //check if dataLayerObj contains the same keys and value types as predefined JSON object
}

What I want to do is to see if the object that is passed in the parameters of each function follows the predefined JSON objects.

lvj
  • 138
  • 9
  • You want to do this? https://stackoverflow.com/questions/26049303/how-to-compare-two-json-have-the-same-properties-without-order (check for properties exist) or you want to check if the values are the right type? – golddragon007 Mar 26 '19 at 10:04
  • 1
    This can be used browser -> https://ajv.js.org/ – Keith Mar 26 '19 at 10:08
  • Since this probably will not change at runtime, wouldn't it be better to add a test to the build process of your website? Adding complexity to your GTM setup and an, albeit small, performance penalty for each of your users is not such a great idea. – Eike Pierstorff Mar 26 '19 at 10:21
  • @golddragon007 Thanks for the tips. However, I want to check the type of the value not that the value equals the same value as the predefined JSON object. – lvj Mar 26 '19 at 11:47
  • @EikePierstorff I will not publish any of these test live, instead just use it in the console or in a dev environment in gtm to be able to do quick sanity checks. Thanks for the consideration though. – lvj Mar 26 '19 at 11:48

0 Answers0