This question already has an answer here:
Why does this JSON string fail to parse?
(1个答案)
去年关闭。
我有一个JavaScript字符串,其中的键的值是数组的字符串表示形式:
jsonlint.com说这是有效的。
引发错误(位置8处的意外 token b)。这似乎是关于包含转义引号的引号-但我的字符串似乎符合www.json.org的标准。
谁是正确的? jsonlint.com还是JSON.parse()?
(1个答案)
去年关闭。
我有一个JavaScript字符串,其中的键的值是数组的字符串表示形式:
{
"a": "[\"b\",\"c\"]"
}
jsonlint.com说这是有效的。
JSON.parse('{"a":"[\"b\",\"c\"]"}');
引发错误(位置8处的意外 token b)。这似乎是关于包含转义引号的引号-但我的字符串似乎符合www.json.org的标准。
// set up an object with this pattern
var o = {};
o['a'] = "[\"b\",\"c\"]";
console.dir(o.a); // -> "[\"b\",\"c\"]"
// look at the JSON string version of this object
var j = JSON.stringify(o);
console.dir(j); // -> {"a":"[\"b\",\"c\"]"}
// set up this inside a string and try to parse it
var k = '{"a":"[\"b\",\"c\"]"}';
var l = JSON.parse(k); // -> error
谁是正确的? jsonlint.com还是JSON.parse()?
最佳答案
用javascript编写字符串时,您需要转义\
字符,否则它将被解释。
const ret = JSON.parse('{"a":"[\\"b\\",\\"c\\"]"}');
console.log(ret);
关于javascript - 哪个正确-jsonlint或JSON.parse? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56577146/
10-08 23:02