Home » Javascript » JSON.parse unexpected character error

JSON.parse unexpected character error

Posted by: admin November 30, 2017 Leave a comment

Questions:

I get this error:

JSON.parse: unexpected character

when I run this statement in firebug:

JSON.parse({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":false});

Why is it so? The JSON string seems correct to me and I also tested it using JSHint. The passed object in the above case is a server response with content type set to application/json

Answers:

You’re not parsing a string, you’re parsing an already-parsed object 🙂

var obj1 = JSON.parse('{"creditBalance":0,...,"starStatus":false}');
//                    ^                                          ^
//                    if you want to parse, the input should be a string 

var obj2 = {"creditBalance":0,...,"starStatus":false};
// or just use it directly.

Questions:
Answers:

You can make sure that the object in question is stringified before passing it to parse function by simply using JSON.stringify() .

Updated You line below,

JSON.parse(JSON.stringify({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":false}));

Questions:
Answers:

If your JSON string from server is correct than,
Check the following three points,

  1. Check the URL of GetJSON or whatever Ajax call is right one
  2. Make sure the line, dataType : “json” in your ajax call
  3. Check you properly loaded the jQuery file.