How can I resolve the 'Uncaught SyntaxError: JSON' on my website?

Topic summary

Issue: “Uncaught SyntaxError: Unexpected end of JSON input” occurs on product and collection pages of a Shopify store (Dawn theme 9.0.0). This error typically means JSON.parse received empty or malformed JSON.

Context: Initial advice was to review recent theme/app changes and validate any JSON data being fetched or used on those pages. The requester asked where in the theme to look; another participant couldn’t see the error, but the issue persists.

Latest development: The requester shared the implicated script from the Smartmail (Smartrmail) app. The code POSTs to https://analytics.smartrmail.com/collect and then runs JSON.parse(xhr.responseText) on a 200 response. The posted snippet appears incomplete/malformed (e.g., broken variable declarations like subscriberToken/urlSubscriberToken and undefined params), which could also cause runtime issues. Central artifact: the code snippet is key to understanding the failure.

Likely cause: The endpoint may return an empty or non‑JSON body, triggering JSON.parse failure, compounded by the script’s apparent syntax issues.

Status: No confirmed fix yet. Next steps implied: validate the Smartmail response payload, correct/guard JSON.parse, review/revert recent changes, and/or contact the app provider; check where this script is injected on product/collection templates.

Summarized with AI on January 24. AI used: gpt-5.

Hello,

Running an inspection on my website www.mastrozavattistore.com, I got this error

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse () at xhr.onreadystatechange (v1_shopify.js:119:25).

It appears at collections and products pages.

What should I do to solve this error?

I am using Dawn theme 9.00

1 Like

The error message you encountered, “Uncaught SyntaxError: Unexpected end of JSON input,” suggests that there is an issue with parsing JSON data on your collections and products pages. This error can occur due to various reasons, such as missing or malformed JSON data. Here are some steps you can take to troubleshoot and resolve the issue:

  1. Review recent changes: Consider any recent changes you made to your collections or products pages, including theme modifications, app installations, or custom code updates. If you made any changes around the time the error started appearing, try reverting those changes or double-checking for any potential issues they may have caused.

  2. Validate JSON data: Check the JSON data being fetched or used on the collections and products pages. Look for any missing or improperly formatted JSON syntax. You can use online JSON validators to validate the data and ensure it is correctly structured.

Thank you for your reply!

In the theme where should I look for the problem?

Hi @Quondy

I did not see this in your console. Is this already fix?

Hello @made4Uo nope. The issue is still there

This is the code that causes the error. It is from Smartmail app.

(function() {
  "use strict";
  function setCookie(name,value,days) {
    var expires = '';
    if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days*24*60*60*1000));
      expires = '; expires=' + date.toUTCString();
    }
    document.cookie = name + '=' + (value || '')  + expires + '; path=/';
  }

  function getCookie(name) {
    var cname = name + '=';
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') c = c.substring(1);
      if (c.indexOf(cname) == 0) return c.substring(cname.length, c.length);
    }
    return false;
  }

  function getUrlParams() {
    var vars = {};
    window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
    function(m,key,value) {
      vars[key] = value;
    });
    return vars;
  }

  function buildQuery(params) {
    var q = '';
    for (var key in params) {
      if (params.hasOwnProperty(key)) {
        if (typeof(params[key]) === 'undefined')
          continue;
        q += (q.charAt(q.length - 1) === '/') ? '?' : '&';
        q += key;
        q += '=';
        q += params[key];
      }
    }
    return q;
  }

  function getResourceTitle() {
    var title = document.title,
      pos = -1;
    if ((pos = title.lastIndexOf(' – ')) !== -1) {}
    else if ((pos = title.lastIndexOf(' :: ')) !== -1) {}
    else if ((pos = title.lastIndexOf(' | ')) !== -1) {}
    else if ((pos = title.lastIndexOf(' - ')) !== -1) {}
    if (pos !== -1) {
      title = title.substring(0, pos);
    }
    return title;
  }

  //
  // Init Vars

  var urlParams = getUrlParams(),
    subscriberToken = getCookie('smsub'),
    urlSubscriberToken = urlParams.smsub,
    isTest = urlParams.smtest;

  if (urlSubscriberToken) {
    setCookie('smsub', urlSubscriberToken, 365);
    subscriberToken = urlSubscriberToken;
  }

  //
  // Tracking

  function trackingEnabled() {
    return !!subscriberToken;
  }

  function debug() {
    if (console && isTest) {
      console.log.apply(console, Array.prototype.slice.call(arguments));
    }
  }

  function track(event, params) {
    if (!trackingEnabled()) {
      debug('[sm] error: invalid session');
      return;
    }
    if (!event) {
      debug('[sm] error: invalid `event` parameter');
      return;
    }
    if (!params.resource_type) {
      debug('[sm] error: invalid `resource_type` parameter');
      return;
    }

    params = params || {};
    params.event = event;
    params.subscriber_token = subscriberToken;
    params.resource_title = getResourceTitle();
    params.url = params.url || [location.protocol, '//', location.host, location.pathname].join('');
    if (isTest) {
      params.test = true;
    }

    var url = urlParams.smlocal ? '/collect' : 'https://analytics.smartrmail.com/collect';
    var query = buildQuery(params);
    debug('[sm] track:', event, params, query);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
        var data = JSON.parse(xhr.responseText);
        if (isTest) {
          debug('[sm] track response', data);
        }
      }
    };
    xhr.send(query);
  }

  //
  // Testing

  function getTestEventFromUrl() {
    if (!urlParams.smtracktype || !urlParams.smtrackid) {
      return false;
    }
    return {
      resource_type: urlParams.smtracktype,
      resource_id: urlParams.smtrackid
    };
  }

  var testEvent = getTestEventFromUrl();
  if (isTest && testEvent) {
    track(urlParams.event || 'test', testEvent);
  }

  //
  // Shopify

  function isShopify() {
    return typeof(Shopify) !== 'undefined' && Shopify.shop;
  }

  function initShopify() {
    if (!isShopify() || typeof(ShopifyAnalytics) === 'undefined' || !ShopifyAnalytics.meta) {
    	debug('[sm] shopify disabled');
      return false;
    }

    // Newsletter click event
    if (urlSubscriberToken) {
      track('newsletter_click', {
        resource_type: 'product'
      });
    }

    // Resource events
    if (ShopifyAnalytics.meta.product) {
      track('view', {
        resource_type: 'product',
        resource_id: ShopifyAnalytics.meta.product.id
      });
    } else if (ShopifyAnalytics.meta.page &&
               ShopifyAnalytics.meta.page.resourceType === 'collection') {
      track('view', {
        resource_type: 'collection',
        resource_id: ShopifyAnalytics.meta.page.resourceType
      });
    }

    // Cart events (theme specific)
    Shopify.onItemAdded = function(lineItem) {
    	debug('[sm] shopify event: item added:', lineItem);
      track('add_cart', {
        resource_type: 'product',
        resource_title: lineItem.title,
        resource_id: lineItem.product_id // may be undefined
      });
    };

    Shopify.onCartUpdate = function (cart) {
    	debug('[sm] shopify event: cart update: ', cart);
    };

    debug('[sm] shopify init');
    return true;
  }

  trackingEnabled() && initShopify();
})();

This is the code that causes the error.

(function() {
  "use strict";
  function setCookie(name,value,days) {
    var expires = '';
    if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days*24*60*60*1000));
      expires = '; expires=' + date.toUTCString();
    }
    document.cookie = name + '=' + (value || '')  + expires + '; path=/';
  }

  function getCookie(name) {
    var cname = name + '=';
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') c = c.substring(1);
      if (c.indexOf(cname) == 0) return c.substring(cname.length, c.length);
    }
    return false;
  }

  function getUrlParams() {
    var vars = {};
    window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
    function(m,key,value) {
      vars[key] = value;
    });
    return vars;
  }

  function buildQuery(params) {
    var q = '';
    for (var key in params) {
      if (params.hasOwnProperty(key)) {
        if (typeof(params[key]) === 'undefined')
          continue;
        q += (q.charAt(q.length - 1) === '/') ? '?' : '&';
        q += key;
        q += '=';
        q += params[key];
      }
    }
    return q;
  }

  function getResourceTitle() {
    var title = document.title,
      pos = -1;
    if ((pos = title.lastIndexOf(' – ')) !== -1) {}
    else if ((pos = title.lastIndexOf(' :: ')) !== -1) {}
    else if ((pos = title.lastIndexOf(' | ')) !== -1) {}
    else if ((pos = title.lastIndexOf(' - ')) !== -1) {}
    if (pos !== -1) {
      title = title.substring(0, pos);
    }
    return title;
  }

  //
  // Init Vars

  var urlParams = getUrlParams(),
    subscriberToken = getCookie('smsub'),
    urlSubscriberToken = urlParams.smsub,
    isTest = urlParams.smtest;

  if (urlSubscriberToken) {
    setCookie('smsub', urlSubscriberToken, 365);
    subscriberToken = urlSubscriberToken;
  }

  //
  // Tracking

  function trackingEnabled() {
    return !!subscriberToken;
  }

  function debug() {
    if (console && isTest) {
      console.log.apply(console, Array.prototype.slice.call(arguments));
    }
  }

  function track(event, params) {
    if (!trackingEnabled()) {
      debug('[sm] error: invalid session');
      return;
    }
    if (!event) {
      debug('[sm] error: invalid `event` parameter');
      return;
    }
    if (!params.resource_type) {
      debug('[sm] error: invalid `resource_type` parameter');
      return;
    }

    params = params || {};
    params.event = event;
    params.subscriber_token = subscriberToken;
    params.resource_title = getResourceTitle();
    params.url = params.url || [location.protocol, '//', location.host, location.pathname].join('');
    if (isTest) {
      params.test = true;
    }

    var url = urlParams.smlocal ? '/collect' : 'https://analytics.smartrmail.com/collect';
    var query = buildQuery(params);
    debug('[sm] track:', event, params, query);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
        var data = JSON.parse(xhr.responseText);
        if (isTest) {
          debug('[sm] track response', data);
        }
      }
    };
    xhr.send(query);
  }

  //
  // Testing

  function getTestEventFromUrl() {
    if (!urlParams.smtracktype || !urlParams.smtrackid) {
      return false;
    }
    return {
      resource_type: urlParams.smtracktype,
      resource_id: urlParams.smtrackid
    };
  }

  var testEvent = getTestEventFromUrl();
  if (isTest && testEvent) {
    track(urlParams.event || 'test', testEvent);
  }

  //
  // Shopify

  function isShopify() {
    return typeof(Shopify) !== 'undefined' && Shopify.shop;
  }

  function initShopify() {
    if (!isShopify() || typeof(ShopifyAnalytics) === 'undefined' || !ShopifyAnalytics.meta) {
    	debug('[sm] shopify disabled');
      return false;
    }

    // Newsletter click event
    if (urlSubscriberToken) {
      track('newsletter_click', {
        resource_type: 'product'
      });
    }

    // Resource events
    if (ShopifyAnalytics.meta.product) {
      track('view', {
        resource_type: 'product',
        resource_id: ShopifyAnalytics.meta.product.id
      });
    } else if (ShopifyAnalytics.meta.page &&
               ShopifyAnalytics.meta.page.resourceType === 'collection') {
      track('view', {
        resource_type: 'collection',
        resource_id: ShopifyAnalytics.meta.page.resourceType
      });
    }

    // Cart events (theme specific)
    Shopify.onItemAdded = function(lineItem) {
    	debug('[sm] shopify event: item added:', lineItem);
      track('add_cart', {
        resource_type: 'product',
        resource_title: lineItem.title,
        resource_id: lineItem.product_id // may be undefined
      });
    };

    Shopify.onCartUpdate = function (cart) {
    	debug('[sm] shopify event: cart update: ', cart);
    };

    debug('[sm] shopify init');
    return true;
  }

  trackingEnabled() && initShopify();
})();