是什么导致了第三行上的错误?
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
打开控制台以查看错误
当前回答
当您使用POST或PUT方法时,请确保对主体部分进行了字符串化。
我在这里记录了一个例子 https://gist.github.com/manju16832003/4a92a2be693a8fda7ca84b58b8fa7154
其他回答
您所得到的错误,即“意外的令牌o”,是因为期望JSON,但在解析时获得了一个对象。“o”是单词“object”的第一个字母。
这是我根据以前的回复做的一个函数:它在我的机器上工作,但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;
}
我的问题是,我通过Ajax在PHP回调函数中注释了HTML,该函数正在解析注释并返回无效的JSON。
一旦我删除了带注释的HTML,一切都很好,JSON被解析没有任何问题。
Products是一个数组,可以直接使用:
var i, j;
for(i=0; i<products.length; i++)
for(j in products[i])
console.log("property name: " + j, "value: " + products[i][j]);
它可能发生的原因有很多,但可能是一个无效的字符,所以你可以使用JSON.stringify(obj);它会将对象转换为JSON,但请记住它是一个jQuery表达式。