简体   繁体   中英

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 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?

$.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', ..} ... 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM