Razib
Razib

Reputation: 11163

JSON.parse() not working

I have a json from my server which is -

{"canApprove": true,"hasDisplayed": false}  

I can parse the json like this -

var msg = JSON.parse('{"canApprove": true,"hasDisplayed": false}');
alert(msg.canApprove);  //shows true.

At my ajax response function I caught the same json mentioned earlier by a method parameter jsonObject -

//response function
function(jsonObject){

  //here jsonObject contains the same json -  {"canApprove":true,"hasDisplayed": false}
  //But without the surrounding single quote
  //I have confirmed about this by seeing my server side log.

  var msg = JSON.parse(jsonObject); // this gives the error

}

But now I got the following error -

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

Can anyone tell me why I am getting the error?

Upvotes: 21

Views: 168099

Answers (9)

alan9uo
alan9uo

Reputation: 1131

Your JsonObject seems is a Json Object. The reasons why you can't parse Json from a String:

  • the String is surround by " ". and use \" escape inside. Here is an example:

    "{\"name\":\"alan\",\"age\":34}"

    when you try to parse above string by JSON.parse(), still return the a string:{"name":"alan","age":34}, and \" is replace by ". But use the JSON.parse() function again, it will return the object you want. So in this case,you can do this:

    JSON.parse(JSON.parse("{\"name\":\"alan\",\"age\":34}" ))

  • Your string use ' instead of " . example:

    {'name':'alan','age':34}

    if you try to parse above string by JSON.parse(), may cause error

Upvotes: 35

Wilfred Almeida
Wilfred Almeida

Reputation: 651

This answer might help someone who's storing JSON as a string in SQL databse.

I was storing the value of following

JSON.stringify({hi:hello})

in MySQL. The JSON stored in SQL was {"hi":"hello"}

Problem was when I read this value from db and fed it to JSON.parse() it gave me error.

I tried wrapping it in quotes but didn't work.

Finally following worked

JSON.parse(JSON.stringify(jsonFromDb))

This worked and JSON was parsed correctly.

I know the storing mechanisim might not be appropriate however those were client needs.

Upvotes: 8

Raj
Raj

Reputation: 31

I faced similar problem and now it's solved. I'm using ASP.Net MVC to send value to .js file. The problem was that I was returning JsonResult from the Action method, because of this JSON.parse was failing in .js file. I changed the return type of Action method to string, now JSON.parse is working fine.

Upvotes: 0

Danny Sofftie
Danny Sofftie

Reputation: 1051

As someone mentioned up there, this actually fixes the problem. What I learnt from this is that may be how PHP encodes a json object is not familiar to JavaScript.

var receivedData = data.toString()
receivedData = JSON.parse(receivedData)
console.log(receivedData.canApprove)

This will work.

Upvotes: -1

Emmanouil Chountasis
Emmanouil Chountasis

Reputation: 590

Here is an example of how to make an ajax call and parse the result:

var query = {
    sUserIds: JSON.stringify(userIds),
};

$.ajax({
    type: "POST",
    url: your-url,
    data: JSON.stringify(query),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: true,
    success: function (response) {
        var your_object = JSON.parse(response.d);
    }, 
    failure: function (msg) {
        alert(msg);
    },
    error: function (a, b, c) {

    }
});

Upvotes: 1

baao
baao

Reputation: 73241

Its already an object, no need to parse it. Simply try

alert(jsonObject.canApprove)

in your response function.

Json.parse is expecting a string.

Upvotes: 4

R3tep
R3tep

Reputation: 12864

Your jsonObject seems already parsed, you need to test if this is the case.

function(jsonObject){
    var msg = (typeof jsonObject == "object" ? jsonObject : JSON.parse(jsonObject));
}

It's also possible that your call back is empty, it's generates the same error if you try to parse an empty string. So test the call back value.

function(jsonObject){
    if(jsonObject) {
       var msg = (typeof jsonObject == "object" ? jsonObject : JSON.parse(jsonObject));
    }
}

Upvotes: 2

Yagiz
Yagiz

Reputation: 1033

var text = '{"canApprove": true,"hasDisplayed": false}';

var parsedJSON = JSON.parse(text);

alert(parsedJSON.canApprove);

This works. It is possible that you use " instead of ' while creating a String.

Upvotes: 1

taxicala
taxicala

Reputation: 21759

I dont think you should call JSON.parse(jsonObject) if the server is sending valid JSON as it will be parsed automatically when it retrieves the response. I believe that if You set the Content-type: application/json header it will be parsed automatically.

Try using jsonObject as if it was already parsed, something like:

console.log(jsonObject.canApprove);

Without calling JSON.parse before.

Upvotes: 13

Related Questions