是什么导致了第三行上的错误?
Var product = [{ “名称”:“披萨”, “价格”:“10”, “数量”:“7” },{ “名称”:“Cerveja”, “价格”:“12”, “数量”:“5” },{ “名称”:“汉堡”, “价格”:“10”, “数量”:“2” },{ “名称”:“Fraldas”, “价格”:“6”, “数量”:“2” }); console.log(产品); var b = JSON.parse(products);//意外令牌o
打开控制台以查看错误
是什么导致了第三行上的错误?
Var product = [{ “名称”:“披萨”, “价格”:“10”, “数量”:“7” },{ “名称”:“Cerveja”, “价格”:“12”, “数量”:“5” },{ “名称”:“汉堡”, “价格”:“10”, “数量”:“2” },{ “名称”:“Fraldas”, “价格”:“6”, “数量”:“2” }); console.log(产品); var b = JSON.parse(products);//意外令牌o
打开控制台以查看错误
当前回答
[
{
"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内容。
其他回答
在调用JSON.parse()时,另一个可能导致“SyntaxError: Unexpected token”异常的问题是在字符串值中使用以下任何一种:
新行字符。 制表符(是的,可以用Tab键生成的制表符!) 任何独立的斜杠\(但出于某种原因不是/,至少在Chrome上不是)。
(完整列表请参见这里的字符串部分。)
例如,下面的代码会让你得到这个异常:
{
"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格式和大量文本中非常不可读。
这是我根据以前的回复做的一个函数:它在我的机器上工作,但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 characters
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;
}
我所犯的错误是将null(不知情)传递给JSON.parse()。
所以它在JSON的0号位置抛出了意外令牌n。
但是当你在JSON.parse()中传递一些不是JavaScript对象的东西时,就会发生这种情况。
我发现同样的问题与JSON.parse(inputString)。
在我的例子中,输入字符串来自我的服务器页面(返回一个页面方法)。
我打印了typeof(inputString) -它是字符串,但仍然发生错误。
我还尝试了JSON.stringify(inputString),但它没有帮助。
后来我发现这是一个问题与新的行操作符[\n],在一个字段值。
我做了一个替换(与一些其他字符,把新的行返回解析后),一切都很好。
您应该在这里验证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