While Developing features with Magento and javascript, sometimes you are facing an error in the browser console for the unexpected token defined in JSON and that will break your Magento functionality on that page.
This type of error we are facing is due to tiny mistakes in javascript JSON Declaration in our code.
This error is coming because our javascript snippet declaration using script text x-magento-init syntax has minor mistakes.
Code With Error:
<script type="text/x-magento-init"> { "*": { "Magento_Ui/js/core/app" : { "components" : { 'customComponent': { "component": "MY_COMPONENT_PATH" } } } } } </script>
Above JS Syntax in template file throws an error because we have defined customComponent using the single quote(‘).
When you declare any javascript related stuff inside object created by <script type=”text/x-magento-init”></script> tag, all the key value pair must be in double quote.
In Magento, Define Javascript Object is converted to JSON format while the page is rendering.
The JSON standard requires double quotes and will not accept single quotes for the parser.
Resolution:
All the Key Value Pair Must be in the Double Quote.
<script type="text/x-magento-init"> { "*": { "Magento_Ui/js/core/app" : { "components" : { "customComponent": { "component": "MY_COMPONENT_PATH" } } } } } </script>
Only Accepted values inside { } are double-quoted otherwise throws an error.