[英]“JSON.parse(str)” returns “Unexpected token c” but str is a string
I am trying the following (below), but when I want to wrap the JSON.parse then I get an error Unexpected Token C. I checked online for similar problems and it says that the input is already an object, thus the reason for throwing this error. 我正在尝试以下(以下),但是当我想包装JSON.parse时,我得到一个错误的意外令牌C.我在线检查了类似的问题,它说输入已经是一个对象,因此抛出的原因这个错误。 However, I tried typeof str and it returned me String.
但是,我尝试了typeof str,它返回了String。 Also accessing it by piecesString[0].col did not work - thus my input is not an object but indeed a string.
另外,通过piecesString [0] .col访问它也不起作用-因此,我的输入不是对象,而是字符串。 What went wrong?
什么地方出了错?
function generatePieces(nbPieces) {
console.log("** nbPieces: " + nbPieces)
var piecesString = "";
var piecesArray = [];
var colIter = 0;
var rowIter = 0;
for (var i = 0; i <= (nbPieces*nbPieces-1); i++) {
piecesString = piecesString + "{col:" + colIter + ",row:" + rowIter + "},"
colIter = colIter + 1;
if (colIter == (nbPieces)) {
//console.log("colIter = nbPieces")
colIter = 0;
rowIter = rowIter +1;
}
}
piecesString = piecesString.substring(0, piecesString.length - 1);
piecesString = "[" + piecesString + "]"
piecesString = '' + piecesString
console.log(piecesString)
piecesArray = JSON.parse(piecesString);
//console.log(piecesString)
}; // end generate pieces
str
is a JS string, but isn't a string representation of a JSON text. str
是一个JS字符串,但不是JSON文本的字符串表示形式。
A property name in JSON must be a string, not an identifier. JSON中的属性名称必须是字符串,而不是标识符。
{ col: 123 }
is a valid JavaScript object literal, but invalid JSON. { col: 123 }
是有效的JavaScript对象文字,但无效的JSON。
{ "col": 123 }
is OK in both. { "col": 123 }
都可以。
Do not attempt to build JSON by mashing strings together. 不要尝试通过将字符串混在一起来构建JSON。 It is more trouble then it is worth.
那就麻烦了,那就值得了。 Build a data structure in whatever programming language you are using at the time (JavaScript in this case) and then pass it through a JSON serialiser.
使用当时使用的任何编程语言(在这种情况下为JavaScript)构建数据结构,然后将其传递给JSON序列化器。
var pieces = [];
for (var i = 0; i <= (nbPieces*nbPieces-1); i++) {
var piece = { col: colIter, row: rowIter };
pieces.push(piece);
}
var json_text = JSON.stringify(pieces);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.