··
134
·
2024-08-14 16:28

JSON Parse报错: Unterminated string

我在JSON parse函数中使用转义引号时,遇到了一个常见的问题。如果存在转义引号,在本例中为“test”,则会导致以下错误

'SyntaxError: JSON Parse error: Unterminated string'.

var information = JSON.parse('[{"-1":"24","0":"","1":"","2":"","3":"0.0000","4":"","5":"0.00","6":"0.00","7":"1.00","8":"0","9":"false","10":"false","11":[""],"12":"","13":"","14":"test\""}]');

JSON Lint验证该JSON为有效的。

Share Favourite Flag

1 answer

你需要像这样"test\\""多加一个转义符号

var information = JSON.parse('[{"-1":"24","0":"","1":"","2":"","3":"0.0000","4":"","5":"0.00","6":"0.00","7":"1.00","8":"0","9":"false","10":"false","11":[""],"12":"","13":"","14":"test\\""}]');

document.body.innerHTML = '<pre>' + JSON.stringify(information, null, 4) + '</pre>';

第一个反斜杠转义javascript字符串文字中的第二个反斜杠。第二个反斜杠转义JSON字符串文字中的引号。

所以它被解析了两次,需要转义两次。

因此,即使它是有效的JSON,您也需要一个javascript字符串文本的转义符,来转义JSON中使用的转义符。

Answer at 2024-08-14 16:43:15
Flag
Get connected with us on social networks! Twitter

©2024 Guangzhou Sinephony Technology Co., Ltd All Rights Reserved