zomato
zomato

Reputation: 71

Accessing child object of json

I have this json object:

var jst =   {"cust":[{"email":"[email protected]", "url":"www.uzti.com"},{"email":"[email protected]", "url":"www.url.com"}]}

Whenever I do jst.cust[0].email. Javascript shows me undefined

More detailed code:

$.ajax(
        {
            type:'GET',
            url:'/ajax_res.php',
            data:"q="+id,
            success: function(data){
                console.log(data);

                var jst = JSON.parse(data);
                console.log(jst);
                console.log(jst.cust[0].email);

                /*$.each(json.cust, function(index, element) {
                    console.log(element.email); 
                });*/

                //alert(json[0]);
            }
        }
        );

Upvotes: 0

Views: 49

Answers (3)

Shyju
Shyju

Reputation: 218762

You don't need to parse it using JSON.parse. You can simply access the JavaScript object properties of the json data received.

 success: function(data){
   alert(data.cust[0].email);
}

Here is a working sample

If you want to access each item in the cust array,

if(data.cust)
{
   $.each(data.cust,function(indx,item){    
         alert(item.email);        
   });
}

Here is a working sample for that.

Upvotes: 0

Skyyy
Skyyy

Reputation: 1569

Following string/json needs to be enclosed by quotes

Change this to

var jst =   {"cust":[{"email":"[email protected]", "url":"www.uzti.com"},{"email":"[email protected]", "url":"www.url.com"}]}

this

var jst =   '{"cust":[{"email":"[email protected]", "url":"www.uzti.com"},{"email":"[email protected]", "url":"www.url.com"}]}';

Here is working example

 var jst =   '{"cust":[{"email":"[email protected]", "url":"www.uzti.com"},{"email":"[email protected]", "url":"www.url.com"}]}';

var jst = JSON.parse(jst);
alert(jst.cust[0].email);

Upvotes: 1

Kaushik
Kaushik

Reputation: 2090

Put a debugger;

use typeof function to determine whether your data is object or string.

$.ajax({
  type: 'GET',
  url: '/ajax_res.php',
  data: "q=" + id,
  success: function(data) {
    debugger;
------^    
    var jst = JSON.parse(data);
    console.log(jst.cust[0].email);

  }
});

then check that you're getting right thing what You're expecting.

Then in your console try to access that data.

var test = JSON.parse('{"cust":[{"email":"[email protected]", "url":"www.uzti.com"},{"email":"[email protected]", "url":"www.url.com"}]}');

test.cust[0].email
o/p - "[email protected]"

You're doing right way. Just recheck your code.

Upvotes: 0

Related Questions