lorraine batol
lorraine batol

Reputation: 6281

How to Parse JSON Object/Array in Ajax

How will I be able to get the value of updated in this json that is from my web service:

{"listener":{"id":"1","updated":"false"}}

Here's what I've tried:

$.ajax({
       ...
        success : function(data) {            
            console.log("received listener: " + data);            
            var received = JSON.parse(JSON.stringify(data));                              
            var listener = received.listener;  
            var length = listener.length;
            //alert('returned json' + data + ' no. of products received: ' + length);
            console.log('returned json' + listener + ' no. of listener received: ' + length); //it says undefined for the length

            var updated = listener[0].updated;

        }
    });

Thanks.

Upvotes: 1

Views: 8356

Answers (1)

Hamish
Hamish

Reputation: 23354

Firstly, this line doesn't make sense:

var received = JSON.parse(JSON.stringify(data));    

JSON.stringify converts a JSON structure to a string, and JSON.parse does the opposite. In other words:

var received = data.listener; // is equivalent.

Secondly, received is an object:

{"id":"1","updated":"false"}

It's not an array, so it does not have a length property. If you were looking to get the id of the received object then you'd obviously use:

var updated = listener.id;

For your code to work data would have to look like this:

{"listener":[{"id":"1","updated":"false"}]}

Upvotes: 2

Related Questions