0

I have a JSON response in JavaScript that looks like this:

{"opt1":"2.92","opt2":"4.24","opt3":"6.36"};

This is the result of applying console.log(data) where data is the response:

success: function(data){
            console.log("Ajax succeeded");
            console.log(data);
            console.log(data.opt1);
        },

However, I cannot access the value of opt1. The console indicates undefined. Any ideas why this could be the case? The JSON is valid, I checked it.

EDIT

The server in this case uses the json_encode function in PHP to convert an array to JSON. I have tried removing the semicolon at the end, this still gives me an undefined value for opt1. I also tried setting the dataType of the ajax call, that results in an error, indicating there is an unexpected character.

3
  • 1
    Does it really have a semicolon on the end? That's not valid JSON. Are you sure console.log(data) isn't logging the JSON string as a string? If you didn't explicitly tell jQuery that you're expecting JSON it tries to guess what format the response is, and I would guess that since your string is not valid JSON it is not parsing it for you so you can't access properties. Commented May 16, 2013 at 11:45
  • Show more of the code -- are you specifying dataType: "json" in the AJAX call, or is the server sending Content-type: application/json? Commented May 16, 2013 at 11:50
  • @PankajGarg: 1. The answer you're pointing to has nothing whatsoever to do with the problem the OP has outlined. 2. Nagging the OP to look at your answer is not cool on SO. When you posted your answer, the OP was notified of that. That is sufficient. Posting a comment (much less an unnecessarily-boldfaced one) is neither appropriate nor useful. Commented May 16, 2013 at 13:10

4 Answers 4

5

It sounds like data may actually be a string, not an object.

Two things you need to do:

First: If that semicolon is really there, the response you're getting is not valid JSON. You'll want to fix that by removing the semicolon server-side. (But see below.)

Second: Then, you'll want to make sure the JSON string is deserialized into an object. Several ways to do that:

  1. It will happen automatically if your server replies with the correct Content-Type header (application/json). This is the best way.

  2. If for some reason that's not the case and you can't make it the case, add dataType: 'json' to your ajax call.

  3. If for some reason you can't do that, you can manually parse the JSON string via $.parseJSON, e.g.:

    data = $.parseJSON(data);
    

    (Note that parseJSON will happily use the browser's built-in JSON.parse if it has one. If the browser doesn't have one, jQuery will use its own.)


If for some reason you can't remove the invalid ; server-side, you can work around it:

  1. Add dataType: 'text' to your ajax call

  2. In success:

    data = $.parseJSON(data.replace(/;$/, ''));
    

    That will remove the semicolon if it's there, and then parse the result.

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

3 Comments

That last suggestion worked for me! Still don't quite get how this can happen though. Where did the semicolon even come from? It was just an array directly converted to a JSON object using json_encode
@danvdende: I'm glad that last option worked for you! json_encode definitely doesn't put a semicolon on, so I'm thinking there must be some stray output further down in the PHP file that's appending it...?
I checked the entire file, there's not other echo there... It's very odd indeed
0

It's probably due to your response coming back as a string from the server (i've had the same issue)... try:

success: function(data){
     var json = $.parseJSON(data);
     console.log("Ajax succeeded");
     console.log(json);
     console.log(json.opt1);
},

5 Comments

You would need $.parseJSON(data), not data.toJSON().
Changed to parseJSON... I got toJSON from w3schools.com/jsref/jsref_tojson.asp, but realised that's just a Date method.
Tried $.parseJSON(data), that gives me Uncaught SyntaxError: Unexpected token ;
I'm guessing that's to do with the end semicolon not parsing then - can you remove this and try the parsing?
And, thus, my noted mistake.
0

Try jQuery.parseJSON(obj).

jQuery.parseJSON() Takes a well-formed JSON string and returns the resulting JavaScript object.

Use it in this way :

var str = '{"opt1":"2.92","opt2":"4.24","opt3":"6.36"}';
var obj = jQuery.parseJSON(str);
console.log(obj.opt1);

Comments

0

Use native call

json = JSON.parse(data);

or make the parameter of ajax as json like this..

$.ajax({
  url : blahblah,
  dataType : 'json',
  .....
});

In this case your response is automatically converted to json

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.