是什么导致了第三行上的错误?
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
打开控制台以查看错误
当前回答
这是我根据以前的回复做的一个函数:它在我的机器上工作,但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.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);
我的问题是,我通过Ajax在PHP回调函数中注释了HTML,该函数正在解析注释并返回无效的JSON。
一旦我删除了带注释的HTML,一切都很好,JSON被解析没有任何问题。
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
现在这是一个JavaScript对象数组,而不是JSON格式。要将其转换为JSON格式,需要使用一个名为JSON.stringify()的函数。
JSON.stringify(products)