119

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

0

3 Answers 3

230

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.
5
  • I want to upvote for the first sentence, but why would you re-parse?
    – Evan Davis
    Dec 15, 2011 at 18:39
  • 1
    @MarcelKorpel, Mathletics: Right. Updated.
    – kennytm
    Dec 15, 2011 at 18:42
  • @Mathletics By all accounts JSON.parse does some security check. N.T.
    – B.F.
    Apr 15, 2014 at 9:33
  • 5
    That's hilarious. Love it. <3 May 21, 2015 at 13:19
  • 1
    I am getting undefined on data.results (data is a JSON object). Stack is telling me to make it a js object by data = JSON.parse(data). But I am getting JSON.parse unexpected character error.
    – KasparTr
    Feb 9, 2016 at 16:08
41

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

Updated your line below,

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

or if you have JSON stored in some variable:

JSON.parse(JSON.stringify(yourJSONobject));
2
  • 4
    JSON.stringify is the boss.
    – Kenmeister
    Oct 31, 2016 at 5:55
  • Thanks a lot, saves a lot of time. Apr 30, 2022 at 17:50
0

Not true for the OP, but this error can be caused by using single quotation marks (') instead of double (") for strings.

The JSON spec requires double quotation marks for strings.

E.g:

JSON.parse(`{"myparam": 'myString'}`)

gives the error, whereas

JSON.parse(`{"myparam": "myString"}`)

does not. Note the quotation marks around myString.

Related: https://stackoverflow.com/a/14355724/1461850

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.