ewom2468
ewom2468

Reputation: 841

Parsing Json Array In Ajax Response

I am working with an application that makes an ajax call and gets a json response. The response is shown below:

    "msg":"successful.","data":{"fee":"100","balance":{"0":"12180"},"status":{"0":"0"}}

The code application logic tests for the value of the "status" field and checks if it is zero before populating a textbox with the response.

The issue is that the "status" field is not being accessed correctly..(i believe) therefore the condition to display the response is never true.

The code is :

   if(data_array.data.status == 0) {/// do stuff

I am of the opinion that this method of accessing the status field is wrong..

I tried this

   if(data_array.data.status.0 == 0) {///

but i am getting an error.... should i try..

    data_array.data.status[0]==0...

How can i access the "status" field value?

Thanks

Upvotes: 0

Views: 4338

Answers (3)

castletheperson
castletheperson

Reputation: 33466

Uncaught SyntaxError: Unexpected token :

The error has doesn't have to do with accessing the field improperly (although you should be using [0] or ["0"]). Surround your JSON with curly braces {} and it will fix the parsing error.

var obj = {"msg": "successful.","data":{"fee": "100","balance":{"0": "12180"},"status":{"0":"0"}}};
<button onclick="alert(obj.data.status[0]);">Click me!</button>

Upvotes: 0

krato
krato

Reputation: 1246

Did you parse the JSON string? If not, try the following:

jsonStr = '{"msg":"successful.","data":{"fee":"100","balance":
{"0":"12180"},"status":{"0":"0"}}}';

jsonObj = JSON.parse(jsonStr);
status = jsonObj.data.status[0];
if(status == 0) { 
    // do some code 
}

Upvotes: 1

ma-jo-ne
ma-jo-ne

Reputation: 147

TRY:

   var obj = jQuery.parseJSON(e);
   var status = obj.status["0"];

Upvotes: 0

Related Questions