Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON data using jQuery

I would like to parse some JSON data but am not sure what I am doing wrong.

The code I am using is as follows:

$.getJSON('bd/getuserDetails',userID,function(data) {
    $.each(data.UserDTO,function(index, value){
         alert(value);
    });
});

In my Java action class I am populating UserDTO with relevant details like name, age, etc.

The above code is able to parse my object, but my intentions are to access the value based on the name like alert(value.name); //user name. Currently it's parsing and displaying the values but I am not able to determine the name for the given value.

How can I access the collection with the name for the corresponding value?

like image 428
Umesh Awasthi Avatar asked Sep 14 '26 06:09

Umesh Awasthi


1 Answers

$.getJSON('bd/getuserDetails',userID,function(data) {
    $.each(data.UserDTO,function(key, value){
         alert(key + ' : ' + value);
    });
});

Suppose if your data.UserDTO is like:

data.UserDTO = {'name' : 'one', 'title' : 'Mr', ..};

then in above loop:

key => name, title...

value => one, Mr...

But

if your

data.UserDTO = [ {'name' : 'one', 'title' : 'Mr', ..}, 
                 {'name' : 'two', 'title' : 'Mrs', ..} 
               ];

then above loop:

key => 0,1... (index of each object within that array)

value => {'name' : 'one', 'title' : 'Mr', ..}, {'name' : 'two', 'title' : 'Mrs', ..} ... 
like image 51
thecodeparadox Avatar answered Sep 16 '26 18:09

thecodeparadox