未捕获的语法错误:JSON 中位置 0 处出现意外的标记 u

问题描述 投票:0回答:9

仅在结帐和单个产品页面上,我在控制台日志中收到以下错误:

VM35594:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at run (layout.min.js:9)
    at app.min.js:1
    at main.min.js:2
    at Object.execCb (require.min.js:112)
    at Module.check (require.min.js:56)
    at Module.<anonymous> (require.min.js:72)
    at require.min.js:11
    at require.min.js:74
    at each (require.min.js:3)

我正在使用一页结帐扩展,但是当我禁用该扩展时,错误仍然显示。我认为这可能与产品页面上的评论有关(因为我将评论移出了选项卡),但撤消该更改并没有修复产品页面上的错误。

javascript json syntax-error magento2
9个回答
252
投票

在控制台中尝试一下:

JSON.parse(undefined)

您将得到以下结果:

Uncaught SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at <anonymous>:1:6

换句话说,您的应用程序正在尝试解析

undefined
,这不是有效的 JSON。

造成这种情况有两个常见原因。首先,您可能引用了一个不存在的属性(如果不在严格模式下,甚至引用了一个不存在的变量)。

window.foobar = '{"some":"data"}';
JSON.parse(window.foobarn)  // oops, misspelled!

第二个常见原因是无法首先接收 JSON,这可能是由于客户端脚本忽略错误并在不应该发送请求时发送请求造成的。

确保服务器端和客户端脚本都在 严格模式 下运行,并使用 ESLint 对它们进行 lint 检查。这会给你很大的信心,没有错别字。


13
投票

正如 @Seth Holladay @MinusFour 评论的那样,您正在解析一个

undefined
变量。
尝试在解析之前添加
if
条件。

if (typeof test1 !== 'undefined') {
  test2 = JSON.parse(test1);
}

注意:这只是对

undefined
情况的检查。任何其他解析问题仍需要处理。


8
投票
localStorage.clear()

这将清除存储的数据。然后刷新,一切就应该开始工作了。


4
投票

您的应用程序正在尝试解析未定义的 JSON Web 令牌。此类故障可能是由于本地存储的错误使用而导致的。尝试清除本地存储。

Google Chrome 示例:

  1. F12
  2. 申请
  3. 本地存储
  4. 全部清除

2
投票

对我来说,发生这种情况是因为我的页面中有一个空组件 -

<script type="text/x-magento-init">
   {
   ".page.messages": {
       "Magento_Ui/js/core/app": []        
      }
   }

删除这段代码解决了问题。


0
投票

这是由于页面上出现干扰

messages
。页面上有多个框架,它们使用窗口消息事件和对象与页面进行通信。其中很少有第三方服务,例如用于管理 cookie 的
cookieq
,或者可能是
cartwire
电子商务集成服务。

您需要处理 onmessage 事件来检查消息来自何处,然后相应地解析 JSON。

我遇到了类似的问题,其中一个集成传递 JSON 对象,另一个集成传递以

u

开头的字符串

0
投票

如果您得到

Uncaught SyntaxError: Unexpected token u in JSON at position 0
那么您可以执行以下快速检查:

jsObj = JSON.parse(data)
  1. 数据 - 检查数据是否未定义

  2. 数据 - 检查数据是否为有效的

    JSON 字符串

  3. 数据 - 检查数据是否被不需要的空格损坏
  4. data = data.trim(); // remove the unwanted whitespace jsObj = JSON.parse(data);

  5. data - 检查接收到的数据是否使用正确的编码格式('
  6. utf8','utf16le','ucs2'

    fs.readFile(file, 'utf8', function(err, data) { ... }); fs.readFile(file, 'utf16le', function(err, data) { ... }); // le - little endian fs.readFile(file, 'ucs2', function(err, data) { ... }); // kind of 'utf16le'

    
        

0
投票

if(res){ let apiResponse = JSON.parse(res); }

它会起作用的。


-2
投票

这就是我收到错误时代码的样子:

request.onload = function() { // This is where we begin accessing the Json let data = JSON.parse(this.response); console.log(data) }

这就是我为了得到我想要的结果而改变的:

request.onload = function() { // This is where we begin accessing the Json let data = JSON.parse(this.responseText); console.log(data) }

所以我真正做的就是改变
    
this.response

this.responseText
    

© www.soinside.com 2019 - 2024. All rights reserved.