Javascript 未捕获的语法错误:JSON.parse 的意外令牌

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14432165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:44:27  来源:igfitidea点击:

Uncaught SyntaxError: Unexpected token with JSON.parse

javascriptjqueryjson

提问by coiso

what causes this error on the third line?

是什么导致第三行出现此错误?

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

Open console to view error

打开控制台查看错误

回答by SLaks

productsis an object. (creating from an object literal)

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

JSON.parse()is used to convert a stringcontaining JSON notation into a Javascript object.

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

Your code turns the object into a string (by calling .toString()) in order to try to parse it as JSON text.
The default .toString()returns "[object Object]", which is not valid JSON; hence the error.

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

回答by EdH

Let's say you know it's valid JSON but your are still getting this...

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

In that case it's likely that there are hidden/special characters in the string from whatever source your getting them. When you paste into a validator, they are lost - but in the string they are still there. Those chars, while invisible, will break JSON.parse()

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

If sis your raw JSON, then clean it up with:

如果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);

回答by Onur Y?ld?r?m

It seems you want to stringifythe object. So do this:

看来您想对对象进行字符串化。所以这样做:

JSON.stringify(products);

The reason for the error is that JSON.parse()expects a Stringvalue and productsis an Array.

错误的原因是JSON.parse()期望一个String值并且products是一个Array.

Note: I think it attempts json.parse('[object Array]')which complains it didn't expect token oafter [.

注意:我认为它试图json.parse('[object Array]')抱怨它o[.

回答by Derin

I found the same issue with JSON.parse(inputString).

我发现了同样的问题JSON.parse(inputString)

In my case the input string is coming from my server page [return of a page method].

在我的情况下,输入字符串来自我的服务器页面[return of a page method]

I printed the typeof(inputString)- it was string, still the error occurs.

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

I also tried JSON.stringify(inputString), but it did not help.

我也尝试过JSON.stringify(inputString),但没有帮助。

Later I found this to be an issue with the new line operator [\n], inside a field value.

后来我发现这[\n]是字段值中的 new line operator 的问题。

I did a replace [with some other character, put the new line back after parse]and everything is working fine.

我做了一个替换 [用其他字符,在解析后放回新行],一切正常。

回答by Térence

JSON.parse is waiting for a String in parameter. You need to stringify your JSON object to solve the problem.

JSON.parse 正在等待参数中的字符串。您需要对 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

回答by pktangyue

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"}];

change to

改成

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"}]';

回答by hoogw

You should validate your JSON string here.

您应该在此处验证您的 JSON 字符串。

A valid JSON string must have double quotes around the keys:

有效的 JSON 字符串必须在键周围使用双引号:

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

If there are no quotes, it will cause an error:

如果没有引号,则会导致错误:

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

Using single quotes will also cause an error:

使用单引号也会导致错误:

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

回答by att

If there are leading or trailing spaces, it'll be invalid. Trailing/Leading spaces can be removed as

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

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

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

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

回答by tmurphree

Here's a function I made based on previous replies: it works on my machine but YMMV.

这是我根据以前的回复制作的一个功能:它适用于我的机器,但 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;
            }

回答by San

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


Here is your perfect Json that you can parse.

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