0

I am receiving following data from server

"[{\"role_id\":\"1\",\"name\":\"administrator\",\"created_by_user_id\":\"2\",\"time_created_on\":null,\"is_user_based\":\"0\"},{\"role_id\":\"2\",\"name\":\"manager\",\"created_by_user_id\":null,\"time_created_on\":null,\"is_user_based\":\"0\"}]"

which is simply an array of two objects . Even after setting 'dataType' to json I am not receiving native javascript array inside my success callback function but if I use

$.ajaxSetup({
        url:'/public/admin/role/list',
        dataType:'json'

    });


$.ajax({
    success:function(data) {
    alert(data[0].name); // alert box pop up as 'undefined ' 
    var data = $.parseJSON(data); 
    alert(data[0].name) ; //works 
    }
    });
0

2 Answers 2

2

Don't escape the ". They're required for JSON parsing.

[{"role_id":"1","name":"administrator","created_by_user_id":"2","time_created_on":null,"is_user_based":"0"},{"role_id":"2","name":"manager","created_by_user_id":null,"time_created_on":null,"is_user_based":"0"}]
3
  • @jason: What version of jQuery are you using? Commented Jul 3, 2011 at 14:42
  • @jason - the outer quotes make it a string and strings do need inner quotes "quoted". Using parseJSON on the resulting string unpacks the string into an object. You just need to return the object itself. I suspect on the server-side you're double-quoting the quotes \\" and starting the string with "\"[.... Drop the opening/closing quotes and don't double quote on the server and you'll be ok. Commented Jul 3, 2011 at 15:04
  • @tvanfosson: You should post your answer. I think you're right. OP is encoding it twice server side. I get the same result in the console with JSON.stringify( JSON.stringify( [{"role_id":"1",...}] ) ); Commented Jul 3, 2011 at 15:21
0

You have a trailing comma when setting dataType in your ajaxSetup method:

dataType:'json',
               ^

Also I hope those \ in the JSON you have shown here are not part of the actual response from the server. The response should look like this:

[{"role_id":"1","name":"administrator","created_by_user_id":"2","time_created_on":null,"is_user_based":"0"},{"role_id":"2","name":"manager","created_by_user_id":null,"time_created_on":null,"is_user_based":"0"}]
2
  • thanks for pointing that out but it was a mistake during copy and paste. Commented Jul 3, 2011 at 14:36
  • @jason bournem so the server sends the JSON as shown in my answer? If this is the case it should work without the need to call any $.parseJSON. Also ensure that there are no surrounding ". Commented Jul 3, 2011 at 14:41

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.