22

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?

13
  • 7
    That almost certainly means that the JSON has already been parsed. Add console.log(typeof jsonObject); to your response function right before you try to parse it. I bet it's "Object". Commented May 12, 2015 at 14:58
  • 1
    Please read the full question, he is trying to parse the json string and not an already parsed json. It's in his code comments. Commented May 12, 2015 at 15:00
  • 2
    @taxicala this question comes up all the time. That's exactly the error you get if you pass the .toString() output from an already-parsed object into JSON.parse(). Commented May 12, 2015 at 15:02
  • 1
    @R3tep yes that would do it too! The important thing is for the OP to come back to the question and tell us what the console.log() call shows. Commented May 12, 2015 at 15:04
  • 1
    console.log(typeof jsonObject) --> object and console.log(jsonObject) --> [object object] Commented May 12, 2015 at 15:10

9 Answers 9

35

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

Sign up to request clarification or add additional context in comments.

1 Comment

I guess you should use replace function before JSON.parse example : var data = "{\"name\":\"alan\",\"age\":34}" str = data.replace(/\\/g, ''); // then use JSON.pase function var jsonObj =JSON.parse(str);
13

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.

3 Comments

Note that having valid JSON and setting Content-type: application/json are two different things. Having valid JSON usually does not imply automatic parsing.
@taxicala I noticed that if you use dataType:"json" on the ajax() jQuery method, you don´t need to use parse() (you actually get the error told by the OP if you do); but you must use it if you don´t specify dataType:"json". I must investigate why is that. Any clue?
I guess you should use replace function before JSON.parse example : var data = "{\"name\":\"alan\",\"age\":34}" str = data.replace(/\\/g, ''); // then use JSON.pase function var jsonObj =JSON.parse(str);
9

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.

1 Comment

Best answer in my case
4

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

alert(jsonObject.canApprove)

in your response function.

Json.parse is expecting a string.

1 Comment

"Its already valid Json, no need to parse it." JSON always has to be parsed. Maybe you mean "it's an object"?
2

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));
    }
}

1 Comment

"If you send a valid JSON, you don't need to parse it" That is not true in general.
1
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.

3 Comments

But I have jsonObject. How can I convert it to text?
@Razib: I thought you wanted to parse JSON into an object. Do you want to go the other way round now? Why?
Why don't you use jsonObject.toString() and then send it to JSON.parse
1

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) {

    }
});

Comments

0

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.

Comments

-1

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.