是什么导致了第三行上的错误?
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
打开控制台以查看错误
当前回答
假设你知道它是有效的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 characters
s = s.replace(/[\u0000-\u0019]+/g,"");
var o = JSON.parse(s);
其他回答
这是我根据以前的回复做的一个函数:它在我的机器上工作,但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;
}
哦,天哪,之前所有答案中的解决方案对我都不起作用。我刚才也遇到了类似的问题。我设法解决了它与包装与报价。请看截图。喔!
原:
Var product = [{ “名称”:“披萨”, “价格”:“10”, “数量”:“7” },{ “名称”:“Cerveja”, “价格”:“12”, “数量”:“5” },{ “名称”:“汉堡”, “价格”:“10”, “数量”:“2” },{ “名称”:“Fraldas”, “价格”:“6”, “数量”:“2” }); console.log(产品); var b = JSON.parse(products);//意外令牌o
您应该在这里验证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
似乎您想要对对象进行字符串化,而不是解析。所以这样做:
JSON.stringify(products);
错误的原因是JSON.parse()期望一个String值,而products是一个Array。
注意:我认为它尝试json。parse('[object Array]'),它会抱怨在[后面没有token o。
它可能发生的原因有很多,但可能是一个无效的字符,所以你可以使用JSON.stringify(obj);它会将对象转换为JSON,但请记住它是一个jQuery表达式。