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

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

打开控制台以查看错误


当前回答

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

其他回答

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

改变

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"}]';

为什么需要JSON.parse?它已经是对象数组格式了。

最好使用JSON。Stringify如下所示:

var b = JSON.stringify(产品);

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

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

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

[
  {
    "name": "Pizza",
    "price": "10",
    "quantity": "7"
  },
  {
    "name": "Cerveja",
    "price": "12",
    "quantity": "5"
  },
  {
    "name": "Hamburguer",
    "price": "10",
    "quantity": "2"
  },
  {
    "name": "Fraldas",
    "price": "6",
    "quantity": "2"
  }
]

下面是您可以解析的完美JSON内容。

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