JSON解析错误:未终止的字符串

时间:2014-12-26 11:17:34

标签: javascript json syntax-error

在JSON解析函数中转义引号时,我遇到了一个常见问题。如果存在转义引用,在这种情况下' test"',则会导致以下错误'语法错误:JSON解析错误:未终止字符串'。

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验证为有效。

4 个答案:

答案 0 :(得分:5)

你必须加倍逃避它,就像"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>';
&#13;
&#13;
&#13;

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

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

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

答案 1 :(得分:0)

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

让doubleslash为我工作......至少在控制台中......尝试一下..

答案 2 :(得分:0)

我通过使用@IgnoreJson通过@RestController在Spring Boot应用程序中解决了此问题

--------- class book ---------------
@OneToMany(mappedBy = "book")
private Set<Chapitre> chapitres = new TreeSet<>();
--------- class chapitre -----------
@ManyToOne(cascade = CascadeType.MERGE)
@JsonIgnore
private Book book;

答案 3 :(得分:-1)

以下是问题:在最后一个对象数组

中使用\'代替\“
\"
\'