$ .parseJSON给出"未捕获的SyntaxError:意外的令牌"

时间:2014-12-30 23:28:10

标签: javascript jquery json parsing

我正在使用JQuery parseJSON解析json字符串

var jsontest = '[{"nombre":"Campa\u00f1a de prueba","parcelas":"10","stampCreacion":"2014-12-30 18:18:26","estado":"1","id":"1","active":"1","camposControl":[{"nombre":"Repetici\u00f3n","tipo":"2","id":"2","active":"1"},{"nombre":"Comentarios","tipo":"1","id":"3","active":"1"}]},{"nombre":"Campa\u00f1a2","parcelas":"10","stampCreacion":"2014-12-30 20:07:36","estado":"1","id":"2","active":"1","camposControl":[{"nombre":"Opciones","tipo":"3","id":"16","active":"1","opciones":[{"nombre":"muchas\r","id":"12","active":"1"},{"nombre":"opciones\r","id":"13","active":"1"},{"nombre":"para mi \r","id":"14","active":"1"},{"nombre":"y para ti","id":"15","active":"1"}]},{"nombre":"numerito por aqui","tipo":"2","id":"17","active":"1"}]}]';



var obj = $.parseJSON(jsontest);

根据jsonlint,它似乎是一个有效的json,但正如你可能在小提琴中看到的那样,它会给出下一个错误:

未捕获的SyntaxError:意外的令牌 - >的jquery-1.11.2.min.js:4

http://jsfiddle.net/6a9qLtq2/

我使用的是chrome BTW

3 个答案:

答案 0 :(得分:1)

我看到的错误是你的逃生'\'。我用\\ uXXXX替换了所有的\ uXXXX代码,我得到的唯一错误就是你的'\ r'。我也删除了'\ r'并让它工作:

    var jsontest = '[{"nombre":"Campa\\u00f1a de prueba","parcelas":"10","stampCreacion":"2014-12-30 18:18:26","estado":"1","id":"1","active":"1","camposControl":[{"nombre":"Repetici\\u00f3n","tipo":"2","id":"2","active":"1"},{"nombre":"Comentarios","tipo":"1","id":"3","active":"1"}]},{"nombre":"Campa\\u00f1a2","parcelas":"10","stampCreacion":"2014-12-30 20:07:36","estado":"1","id":"2","active":"1","camposControl":[{"nombre":"Opciones","tipo":"3","id":"16","active":"1","opciones":[{"nombre":"muchas","id":"12","active":"1"},{"nombre":"opciones","id":"13","active":"1"},{"nombre":"para mi ","id":"14","active":"1"},{"nombre":"y para ti","id":"15","active":"1"}]},{"nombre":"numerito por aqui","tipo":"2","id":"17","active":"1"}]}]';


var obj = $.parseJSON(jsontest);
console.log(obj);

我不确定你要用'\ r'来做什么,但如果你要回车,我想你想要'\ n'。

作为关于转义的注释,你必须记住你在一个字符串中有字符串,所以你必须双重转义(你需要两个反斜杠而不是一个)。

哦,这是叉子http://jsfiddle.net/gok31tqu/

然后进行测试,我做了另一个分支,用“\\ r”替换你的'\ r',它似乎也运行了:

http://jsfiddle.net/9vktyj29/

希望有所帮助。

答案 1 :(得分:-2)

将JSFiddle更新为:

var jsonstringify = JSON.stringify(jsontest);
    var obj = $.parseJSON(jsonstringify);

编码反斜杠

答案 2 :(得分:-2)

use eval(jsonData) will fix this issue..