是什么导致了第三行上的错误?

Var product = [{ “名称”:“披萨”, “价格”:“10”, “数量”:“7” },{ “名称”:“Cerveja”, “价格”:“12”, “数量”:“5” },{ “名称”:“汉堡”, “价格”:“10”, “数量”:“2” },{ “名称”:“Fraldas”, “价格”:“6”, “数量”:“2” }); console.log(产品); var b = JSON.parse(products);//意外令牌o

打开控制台以查看错误


当前回答

我所犯的错误是将null(不知情)传递给JSON.parse()。

所以它在JSON的0号位置抛出了意外令牌n。

但是当你在JSON.parse()中传递一些不是JavaScript对象的东西时,就会发生这种情况。

其他回答

现在这是一个JavaScript对象数组,而不是JSON格式。要将其转换为JSON格式,需要使用一个名为JSON.stringify()的函数。

JSON.stringify(products)

唯一的错误是您正在解析一个已经解析过的对象,因此它抛出一个错误。用这个你就可以走了。

Var product = [{ “名称”:“披萨”, “价格”:“10”, “数量”:“7” },{ “名称”:“Cerveja”, “价格”:“12”, “数量”:“5” },{ “名称”:“汉堡”, “价格”:“10”, “数量”:“2” },{ “名称”:“Fraldas”, “价格”:“6”, “数量”:“2” }); console.log(产品[0]. name);//第0个索引项的名称

如果想打印整个JSON内容,请使用JSON.stringify()。

这是我根据以前的回复做的一个函数:它在我的机器上工作,但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;
}

在我的情况下,在我的JSON字符串中有以下字符问题:

r \ \ t \ r \ n \ n : "

我用其他字符或符号替换了它们,然后又从编码中恢复过来。

它可能发生的原因有很多,但可能是一个无效的字符,所以你可以使用JSON.stringify(obj);它会将对象转换为JSON,但请记住它是一个jQuery表达式。