Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax error from JSON.parse()

Tags:

json

jquery

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.

like image 343
kheya Avatar asked Oct 21 '25 12:10

kheya


2 Answers

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,...'
like image 144
Rocket Hazmat Avatar answered Oct 24 '25 08:10

Rocket Hazmat


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
like image 28
Marc B Avatar answered Oct 24 '25 06:10

Marc B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!