Magento 2 – How to Debug JSON Errors

debugjsonmagento2

After a while of developing (with a colleague) I get this JS error on every page: "SyntaxError: JSON.parse: unexpected character at line 5 column 50 of the JSON data" in file main.js.

This is nice to know but I have no idea what JSON data is causing the problem. main.js is a core file that was not changed. The firefox console does not tell me what data is the issue and where it comes from.

So my question is: how do I debug such errors?

Best Answer

The only JSON.parse command in main.js is in the getData function; specifically, at Line 52:

45 function getData(el) { 46 var data = el.getAttribute(dataAttr); ... 50 return { 51 el: el, 52 data: JSON.parse(data) 53 };

The getData function parses "elements 'data-mage-init' attribute as a valid JSON data." This is the attribute Magento uses to inject a JS component into a phtml file. This leads me to believe that you or your colleague have tried to use this attribute to inject a JavaScript script into a template file, but that the attribute's JSON syntax is malformed, however slightly.

If you haven't injected scripts in too many places, then this alone may be enough to help you pinpoint the problem. If not, you may temporarily insert a console.log command after Line 46 of main.js, like so:

46 var data = el.getAttribute(dataAttr); 47 console.log(data);

This may dump enough data in your Firefox console to help you identify where your script injection has gone awry. Just make sure to restore main.js to its original glory after you're done debugging.

Related Topic