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

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;
}

其他回答

Products是一个对象。(从对象字面量创建)

JSON.parse()用于将包含JSON符号的字符串转换为Javascript对象。

您的代码将对象转换为字符串(通过调用. tostring()),以便尝试将其解析为JSON文本。 默认的.toString()返回"[object object]",这不是有效的JSON;因此出现了错误。

您所得到的错误,即“意外的令牌o”,是因为期望JSON,但在解析时获得了一个对象。“o”是单词“object”的第一个字母。

如果有前导空格或尾随空格,则无效。 后面和前面的空格可以被删除为

mystring = mystring.replace(/^\s+|\s+$/g, "");

删除字符串的前导或尾随空格

似乎您想要对对象进行字符串化,而不是解析。所以这样做:

JSON.stringify(products);

错误的原因是JSON.parse()期望一个String值,而products是一个Array。

注意:我认为它尝试json。parse('[object Array]'),它会抱怨在[后面没有token o。

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

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

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