Syntax error from JSON.parse()

Go To StackoverFlow.com

2

My custom method to get json from string:

function GetJSON(a) {
        if (typeof a !== "string" || !a || a == null) return null;
        a = a.replace(/\r\n|\r|\n|\t/g, '').replace(/\\/g, '/');
        return new Function("return " + a)();
    }

    var notes ='{editable:true,useAjax:false,notes:[{"top":76,"left":411,"width":30,"height":30,"text":"hill","editable":true},{"top":183,"left":556,"width":30,"height":30,"text":"lake","editable":true}]}';

    return GetJSON(notes); //<-- works fine

    //I am trying to replace my custom method with
      return JSON.parse(notes);

But I get syntax error when I call JSON.parse()

What can be wrong?

EDIT: I pasted the actual value that I pass to JSON.parse() from debug output.

2012-04-05 17:20
by kheya
For future reference ("what can be wrong" when you receive a syntax error), syntax error means that your input is syntactically invalid, I.E. it is not following the grammar rules of the language - Esailija 2012-04-05 17:33


4

notes = "{editable:true,useAjax:false,notes:[" + notes + "]}";

You forgot to quote your keys here. It should be:

notes = '{"editable":true,"useAjax":false,"notes":[' + notes + ']}';

The final JSON should be:

var notes ='{"editable":true,"useAjax":false,"notes":[{"top":76,"left":411,...'
2012-04-05 17:28
by Rocket Hazmat
let me try this.. - kheya 2012-04-05 17:33
This was the issue!! Silly me - kheya 2012-04-05 17:35
Yeah, JSON.parse is really strict about syntax :- - Rocket Hazmat 2012-04-05 18:14


2

Your notes portion is missing a , between the two {} sets, making it invalid JSON.

It should be

[..snip..] "editable":true}, ' + '{"top":20,"left"[...snip...]
                           ^^--- missing
2012-04-05 17:21
by Marc B
There seems to be a comma in the code in the question (maybe it was edited?) - Rocket Hazmat 2012-04-05 17:29
Yeah, wasn't there at the time.. - Marc B 2012-04-05 17:30
Ads