Uncaught SyntaxError:带有JSON.parse的意外标记

时间:2013-01-21 03:34:09

标签: javascript jquery json

第三行导致此错误的原因是什么?

var products = [{
  "name": "Pizza",
  "price": "10",
  "quantity": "7"
}, {
  "name": "Cerveja",
  "price": "12",
  "quantity": "5"
}, {
  "name": "Hamburguer",
  "price": "10",
  "quantity": "2"
}, {
  "name": "Fraldas",
  "price": "6",
  "quantity": "2"
}];
console.log(products);
var b = JSON.parse(products); //unexpected token o

打开控制台以查看错误

26 个答案:

答案 0 :(得分:190)

products是一个对象。 (从对象文字创建)

JSON.parse()用于将包含JSON表示法的字符串转换为Javascript对象。

您的代码将对象转换为字符串(通过调用.toString())以尝试将其解析为JSON文本。
默认.toString()返回"[object Object]",这是无效的JSON;因此错误。

答案 1 :(得分:99)

假设你知道它是有效的JSON,但你仍然得到这个......

在这种情况下,你可能会从你获得它们的任何来源的字符串中隐藏/特殊字符。当您粘贴到验证器中时,它们会丢失 - 但在字符串中它们仍然存在。这些字符虽然不可见,但会破坏JSON.parse()

如果s是您的原始JSON,请使用以下命令进行清理:

// preserve newlines, etc - use valid JSON
s = s.replace(/\\n/g, "\\n")  
               .replace(/\\'/g, "\\'")
               .replace(/\\"/g, '\\"')
               .replace(/\\&/g, "\\&")
               .replace(/\\r/g, "\\r")
               .replace(/\\t/g, "\\t")
               .replace(/\\b/g, "\\b")
               .replace(/\\f/g, "\\f");
// remove non-printable and other non-valid JSON chars
s = s.replace(/[\u0000-\u0019]+/g,""); 
var o = JSON.parse(s);

答案 2 :(得分:54)

您似乎想 stringify 该对象。所以这样做:

JSON.stringify(products);

出错的原因是JSON.parse()期望String值,productsArray

注意:我认为json.parse('[object Array]')会在o之后抱怨它不期望令牌[

答案 3 :(得分:27)

我在JSON.parse(inputString)找到了同样的问题。

在我的情况下,输入字符串来自我的服务器页面 [返回页面方法]

我打印了typeof(inputString) - 它是字符串,但仍然发生错误。

我也试过JSON.stringify(inputString),但没有用。

后来我发现这是新行操作符[\n]在字段值中的问题。

我做了替换[与其他角色一起,在解析后将新行放回去] 并且一切正常。

答案 4 :(得分:10)

products = [{"name":"Pizza","price":"10","quantity":"7"}, {"name":"Cerveja","price":"12","quantity":"5"}, {"name":"Hamburguer","price":"10","quantity":"2"}, {"name":"Fraldas","price":"6","quantity":"2"}];

更改为

products = '[{"name":"Pizza","price":"10","quantity":"7"}, {"name":"Cerveja","price":"12","quantity":"5"}, {"name":"Hamburguer","price":"10","quantity":"2"}, {"name":"Fraldas","price":"6","quantity":"2"}]';

答案 5 :(得分:8)

JSON.parse正在等待参数中的String。您需要对JSON对象进行字符串化以解决问题。

products = [{"name":"Pizza","price":"10","quantity":"7"}, {"name":"Cerveja","price":"12","quantity":"5"}, {"name":"Hamburguer","price":"10","quantity":"2"}, {"name":"Fraldas","price":"6","quantity":"2"}];
console.log(products);
var b = JSON.parse(JSON.stringify(products));  //solves the problem

答案 6 :(得分:3)

[
  {
    "name": "Pizza",
    "price": "10",
    "quantity": "7"
  },
  {
    "name": "Cerveja",
    "price": "12",
    "quantity": "5"
  },
  {
    "name": "Hamburguer",
    "price": "10",
    "quantity": "2"
  },
  {
    "name": "Fraldas",
    "price": "6",
    "quantity": "2"
  }
]

这是你可以解析的完美Json。

答案 7 :(得分:2)

这是我根据以前的回复制作的一个功能:它可以在我的机器上运行,但YMMV。

          /**
             * @description Converts a string response to an array of objects.
             * @param {string} string - The string you want to convert.
             * @returns {array} - an array of objects.
            */
            function stringToJson(input) {
              var result = [];

              //replace leading and trailing [], if present
              input = input.replace(/^\[/,'');
              input = input.replace(/\]$/,'');

              //change the delimiter to 
              input = input.replace(/},{/g,'};;;{');

              // preserve newlines, etc - use valid JSON
              //https://stackoverflow.com/questions/14432165/uncaught-syntaxerror-unexpected-token-with-json-parse
            input = input.replace(/\\n/g, "\\n")  
            .replace(/\\'/g, "\\'")
            .replace(/\\"/g, '\\"')
            .replace(/\\&/g, "\\&")
            .replace(/\\r/g, "\\r")
            .replace(/\\t/g, "\\t")
            .replace(/\\b/g, "\\b")
            .replace(/\\f/g, "\\f");
            // remove non-printable and other non-valid JSON chars
            input = input.replace(/[\u0000-\u0019]+/g,""); 

              input = input.split(';;;');

              input.forEach(function(element) {
                // console.log(JSON.stringify(element));

                result.push(JSON.parse(element));
              }, this);

              return result;
            }

答案 8 :(得分:2)

您必须在https://jsonformatter.curiousconcept.com/

处有效的json字符串

有效的json字符串必须有双引号。

JSON.parse({"u1":1000,"u2":1100})       // will be ok

没有报价导致错误

JSON.parse({u1:1000,u2:1100})    
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2

单引号导致错误

JSON.parse({'u1':1000,'u2':1100})    
// error Uncaught SyntaxError: Unexpected token ' in JSON at position 1

答案 9 :(得分:2)

当您使用POST或PUT方法时,请确保将身体部位字符串化。

我在这里记录了一个例子 https://gist.github.com/manju16832003/4a92a2be693a8fda7ca84b58b8fa7154

答案 10 :(得分:2)

调用"SyntaxError: Unexpected token"时可能导致JSON.parse()异常的另一个问题是在字符串值中使用以下任何一项:

  1. 换行符。

  2. 标签(是的,您可以使用Tab键生成的标签!)

  3. 任何独立的斜杠\(但出于某种原因,/,至少不在Chrome上。)

  4. (有关完整列表,请参阅String section here。)

    例如,以下内容将为您提供此异常:

    {
        "msg" : {
            "message": "It cannot
    contain a new-line",
            "description": "Some discription with a     tabbed space is also bad",
            "value": "It cannot have 3\4 un-escaped"
        }
    }
    

    所以应该改为:

    {
        "msg" : {
            "message": "It cannot\ncontain a new-line",
            "description": "Some discription with a\t\ttabbed space",
            "value": "It cannot have 3\\4 un-escaped"
        }
    }
    

    我应该说,在具有大量文本的仅JSON格式中,它非常难以理解。

答案 11 :(得分:1)

希望这有助于其他人。

我的问题是我通过AJAX在PHP回调函数中评论了HTML,它解析了注释并返回了无效的JSON。

一旦我删除了评论的HTML,一切都很好,并且解析了JSON没有问题。

答案 12 :(得分:1)

如果有前导或尾随空格,它将无效。 尾随/前导空格可以删除为

mystring = mystring.replace(/^\s+|\s+$/g, "");

来源:http://www.toptip.ca/2010/02/javascript-trim-leading-or-trailing.html

答案 13 :(得分:1)

您要做的唯一错误是,您正在解析已解析的对象,因此它会引发错误,请使用它,这样您会很方便。

var products = [{
  "name": "Pizza",
  "price": "10",
  "quantity": "7"
}, {
  "name": "Cerveja",
  "price": "12",
  "quantity": "5"
}, {
  "name": "Hamburguer",
  "price": "10",
  "quantity": "2"
}, {
  "name": "Fraldas",
  "price": "6",
  "quantity": "2"
}];
console.log(products[0].name); //name of item at 0th index

如果要打印整个json,请使用JSON.stringify()

答案 14 :(得分:0)

现在显然\r\b\t\f等不是唯一可以解决此错误的问题字符。

请注意,某些浏览器可能对JSON.parse的输入有其他要求。

在浏览器上运行此测试代码:

var arr = [];
for(var x=0; x < 0xffff; ++x){
    try{
        JSON.parse(String.fromCharCode(0x22, x, 0x22));
    }catch(e){
        arr.push(x);
    }
}
console.log(arr);

在Chrome上进行测试,我发现它不允许JSON.parse(String.fromCharCode(0x22, x, 0x22)); x为34,92或0到31。

字符34和92分别是"\个字符,它们通常是预期的并且已正确转义。它的字符0到31会给你带来麻烦。

为帮助调试,在执行JSON.parse(input)之前,请先验证输入中是否包含有问题的字符:

function VerifyInput(input){
    for(var x=0; x<input.length; ++x){
        let c = input.charCodeAt(x);
        if(c >= 0 && c <= 31){
            throw 'problematic character found at position ' + x;
        }
    }
}

答案 15 :(得分:0)

为什么需要JSON.parse?它已经是对象格式数组。

最好使用JSON.stringify,如下所示: var b = JSON.stringify(products);

这可能会对你有帮助。

答案 16 :(得分:0)

天哪,迄今为止提供的所有上述答案的解决方案对我来说都不起作用。我刚才有类似的问题。我设法用报价包装来解决它。查看截图。喔。

enter image description here

<强>原始

&#13;
&#13;
var products = [{
  "name": "Pizza",
  "price": "10",
  "quantity": "7"
}, {
  "name": "Cerveja",
  "price": "12",
  "quantity": "5"
}, {
  "name": "Hamburguer",
  "price": "10",
  "quantity": "2"
}, {
  "name": "Fraldas",
  "price": "6",
  "quantity": "2"
}];
console.log(products);
var b = JSON.parse(products); //unexpected token o
&#13;
&#13;
&#13;

答案 17 :(得分:0)

产品是一个可以直接使用的数组:

var i, j;

for(i=0;i<products.length;i++)
  for(j in products[i])
    console.log("property name: " + j,"value: "+products[i][j]);

答案 18 :(得分:0)

您得到的错误,即“意外令牌o”是因为需要json,但在解析时会获得对象。 “ o”是“对象”一词的第一个字母。

答案 19 :(得分:0)

它的发生可能有多种原因,但可能是由于字符无效而引起的,因此您可以使用JSON.stringify(obj);将对象转换为JSON,但请记住它是一个JQUERY表达式。

答案 20 :(得分:0)

我有这个错误,因为返回json对象的API给出了一个错误(在我的情况下为Code Igniter,当php代码失败时返回html),所以它不是JSON对象。

检查SQL语句和PHP代码,并使用Postman(或其他一些API测试器)对其进行测试

答案 21 :(得分:0)

我正在做的错误是在不知不觉中将null传递到JSON.parse()。

所以它扔了Unexpected token n in JSON at position 0

答案 22 :(得分:0)

这现在是一个 JavaScript 对象数组,而不是 JSON 格式。要将其转换为 JSON 格式,您需要使用一个名为 JSON.stringify()

的函数
JSON.stringify(products)

答案 23 :(得分:-1)

检查此代码。它为您提供了JSON解析错误的清晰解决方案。通常是通过换行符以及json键开始和json键结束之间的空格

发生的
data_val = data_val.replace(/[\n\s]{1,}\"/g, "\"")  
               .replace(/\"[\n\s]{1,}/g, "\"")  
               .replace(/[\n]/g, "\\n") 

答案 24 :(得分:-1)

就我而言,我的 JSON 字符串中存在以下字符问题

  1. \r
  2. \t
  3. \r\n
  4. \n
  5. "

我已经用其他字符或符号替换了它们,然后又从编码中恢复过来。

答案 25 :(得分:-23)

使用eval。它将JavaScript表达式/代码作为字符串并评估/执行它。

eval(inputString);
相关问题