Products that cover the topic Magento 2 Google Analytics 4 (GA4) GTM Extension

Visualize JSON with vanilla Javascript

 

Online Demo

Paste any valid JSON object in the area below to convert it into interactive HTML

 

Supported types and syntax

 

Onto topic

Some of our extensions are quite complex and their descriptions required visualizing some JSON examples into human-readable format as HTML. Moreover, we wanted to have the JSON not only displayed in a tree format but interactive as well so customers can expand or collapse the JSON tree directly in the page and review contents such as dataLayer[] states, pushes etc. mainly related to our GA4 extension for Magento 2 where understanding how module interacts with dataLayer is paramount.

After exploring multiple tools and libraries, we quickly figured that it is hard to justify loading an entire library for displaying a small chunk of code, just like cars, a 2 ton vehicle carries 1 person with total weight of 80 kg. Numbers just didn't add up.

That being said, we have prepared a really basic, really quick, vanilla based Javascript snippet that can handle this simple rendering and allow you to have your JSON displayed in beautiful easy to understand format and rendered as HTML. The idea is simple, we first create a DIV element with data-json attribute where we add the JSON that we need displayed, from then on the script will automatically pick this data and render the JSON inside the very same DIV but this time in human-readable format.

To generate this, we shall use the following short PHP example.

HTML content

{ } php <div  data-json="<?=  htmlspecialchars(json_encode         (                 [                         'root'  =>                           [                                 'items'  =>                                   [                                         [                                                 'item_id'  =>  1,                                                 'item_name'  =>  'Item  A',                                                 'price'  =>  12.5                                         ],                                         [                                                 'item_id'  =>  2,                                                 'item_name'  =>  'Item  B',                                                 'price'  =>  100                                         ]                                 ]                         ]                 ],                   JSON_HEX_APOS         ))  ?>"> </div>

It generates a DIV element with data-json attribute set to desired JSON.

Vanilla Javascript code

Once, we have this element rendered in the page, we can add the actual JS code that will do the rendering.

{ } JS (116 lines of code) (()  =>   {         const  isNumeric  =  (num)  =>  (typeof(num)  ===  'number'  ||  typeof(num)  ===  "string"  &&  num.trim()  !==  '')  &&  !isNaN(num);         const  path  =           {                 show:  'M3  24l18-12-18-12v24zm16.197-12l-15.197  10.132v-20.263l15.197  10.131',                 hide:  'M0  3l12  18  12-18h-24zm12  16.197l-10.132-15.197h20.263l-10.131  15.197'         }         let  svg  =  (node  =>           {                 return  (text  =>                   {                         let  svg  =  node('svg',  {  width:12,  height:  12  });                         svg.appendChild                         (                                 node('path',  {  d:  text,  transform:'scale(0.3  0.3)  translate(0  15)'  })                         );                         return  svg;                 });                  })((n,  v)  =>           {                         n  =  document.createElementNS("http://www.w3.org/2000/svg",  n);                                                  for  (var  p  in  v)                           {                                 n.setAttributeNS(null,  p,  v[p]);                         }                                                  return  n;         });         let  add  =  (element,  parent,  content)  =>           {                 let  e  =  document.createElement(element);                 ('undefined'  !==  typeof  parent  ?  parent  :  document.body).appendChild(e);                 if  ('undefined'  !==  typeof  content)                 {                         e.innerHTML  =  content.toString().length    ?  content  :  '&lt;empty  string&gt;'                 }                 return  e;         };         let  toggle  =  element  =>           {                 let  display  =  element.nextSibling.style.display.indexOf('block')  ?  false  :  true;                 element.nextSibling.style.display  =  display  ?  'none'  :  'block';                 element.previousSibling.parentNode.querySelectorAll('svg  path').forEach(arrow  =>                   {                         arrow.setAttribute('d',  arrow.getAttribute('d')  ?  (display  ?  path.show  :  path.hide)  :  '');                 });                 element.nextSibling.querySelectorAll('div').forEach(element  =>                   {                         element.style.display  =  display  ?  'none'  :  'block';                 });         };         let  json  =  (tree,  parent)  =>           {                 Object.entries(tree).forEach(([key,  value])=>                   {                         let  node  =  add('span',  parent);                         if  ('object'  !==  typeof  value  ||  null  ===  value)                         {                                 node.append(svg(''));                                 add('em',  node,  key  +  ':')                                 let  label  =  add('em',  node);                                 label.dataset.type  =  typeof  value;                                 null  ===  value  ?  add('b',  label,  'NULL')  :  add('em',  label,  value);                                 add('em',  label,  typeof  value).style.color  =  'rgba(220,220,220,1)';                         }                         else                           {                                 node.append(svg(path.show));                                 let  trigger  =  add('em',  node,  key  +  ':  {  ');                                 trigger.style.cursor  =  'pointer';                                 trigger.addEventListener('click',  event  =>                                   {                                         toggle(event.currentTarget);                                   });                                 let  wrapper  =  add('div',  node);                                 wrapper.style.display  =  'none';                                 json(value,  wrapper);                                 add('em',node,'}').style.marginLeft  =  '11px';                         }                 });         };                  document.querySelectorAll('[data-json]').forEach(wrapper  =>           {                 json(JSON.parse(wrapper.dataset.json),  wrapper);         }); })();

Styling

Last but not least, we should also add some CSS in the HEAD

{ } style (css) [data-json]  span  {  margin:5px  0px  5px  0px;  } [data-json]  span,   [data-json]  span  em  {  font-family:  monospace;  display:block;  font-size:12px;  letter-spacing:  0.5px;  font-size:13px;  } [data-json]  span  span  {  margin-left:30px;  } [data-json]  span  em  {  font-style:  normal;  display:  inline;  color:rgb(0,  43,  54);    } [data-json]  span  em  >  em  {  color:#f57e04;    margin:0px  5px  0px  5px;    } [data-json]  span  em[data-type="number"]  >  em  {  color:#4081ec;  } [data-json]  span  em[data-type="boolean"]  >  em  {  color:#34a852}

The result

The result would be beautiful JSON rendered directly in the HTML page as seen below. You can also click any of the elements from the tree to expand or collapse it's contents.

 

 

Extensions for Magento

Anowave is an extension developer for Magento 1.x and Magento 2.x platforms. We provide a wide range of premium extensions for our in-house and public clients. The extensions we offer extend the capabilities of Magento and provide bespoke functionality. They also fill some gaps in the functionality provided by the base platform and help customers choose Magento as their preferred eCommerce platform.

The extensions we offer are part of our full-range Magento service, which also includes a Premium Helpdesk where customers can speak with actual software engineers and have their issues resolved without hassle. Premium-labeled modules also include free installation, configuration, testing, etc.