Loop through JSON object List
Asked Answered
A

8

66

I am returning a List<> from a webservice as a List of JSON objects. I am trying to use a for loop to iterate through the list and grab the values out of the properties. This is a sample of the returning JSON:

{"d":[{"__type":"FluentWeb.DTO.EmployeeOrder",
 "EmployeeName":"Janet Leverling",
 "EmployeeTitle":"Sales Representative",
 "RequiredDate":"\/Date(839224800000)\/",
 "OrderedProducts":null}]}

So I am trying to extract the contents using something like this:

function PrintResults(result) {

for (var i = 0; i < result.length; i++) { 
    alert(result.employeename);
}

How should this be done?

Acetometer answered 29/4, 2009 at 2:4 Comment(1)
IN Java, you need to map the Json into POJO. Once this done you can retrive any value. If its List then iterate(loop) it and get the json value through objectBopp
P
57

had same problem today, Your topic helped me so here goes solution ;)

 alert(result.d[0].EmployeeTitle);
Posset answered 8/5, 2009 at 17:40 Comment(4)
Thank you. This is the conclusion I came to as well. Here is a great post that has the solution detailed. elegantcode.com/2009/05/04/jquery-ajax-with-class-arrays Hope this helps others.Acetometer
the link in the comment above is deadInterinsurance
the link in the comment above is undeadBlackheart
the link in the comment above seems to redirect to linkedinUnderwood
B
68

Be careful, d is the list.

for (var i = 0; i < result.d.length; i++) { 
    alert(result.d[i].employeename);
}
Bawdry answered 29/4, 2009 at 2:6 Comment(2)
Thanks.. but that doesn't return anything either.Acetometer
It should. That is correct. JavaScript is case sensitive. EmployeeNameDebbidebbie
P
57

had same problem today, Your topic helped me so here goes solution ;)

 alert(result.d[0].EmployeeTitle);
Posset answered 8/5, 2009 at 17:40 Comment(4)
Thank you. This is the conclusion I came to as well. Here is a great post that has the solution detailed. elegantcode.com/2009/05/04/jquery-ajax-with-class-arrays Hope this helps others.Acetometer
the link in the comment above is deadInterinsurance
the link in the comment above is undeadBlackheart
the link in the comment above seems to redirect to linkedinUnderwood
K
22

It's close! Try this:

for (var prop in result) {
    if (result.hasOwnProperty(prop)) {
        alert(result[prop]);
    }
}

Update:

If your result is truly is an array of one object, then you might have to do this:

for (var prop in result[0]) {
    if (result[0].hasOwnProperty(prop)) {
        alert(result[0][prop]);
    }
}

Or if you want to loop through each result in the array if there are more, try:

for (var i = 0; i < results.length; i++) {
    for (var prop in result[i]) {
        if (result[i].hasOwnProperty(prop)) {
            alert(result[i][prop]);
        }
    }
}
Kalil answered 29/4, 2009 at 2:7 Comment(1)
This gets me closer.. It still just alerts with [object Object],[object Object]....Acetometer
T
17

Here it is:

success: 
    function(data) {
        $.each(data, function(i, item){
            alert("Mine is " + i + "|" + item.title + "|" + item.key);
        });
    }

Sample JSON text:

{"title": "camp crowhouse", 
"key": "agtnZW90YWdkZXYyMXIKCxIEUG9zdBgUDA"}
Thorfinn answered 18/11, 2010 at 9:56 Comment(0)
L
9

Since you are using jQuery, you might as well use the each method... Also, it seems like everything is a value of the property 'd' in this JS Object [Notation].

$.each(result.d,function(i) {
    // In case there are several values in the array 'd'
    $.each(this,function(j) {
        // Apparently doesn't work...
        alert(this.EmployeeName);
        // What about this?
        alert(result.d[i][j]['EmployeeName']);
        // Or this?
        alert(result.d[i][j].EmployeeName);
    });
});

That should work. if not, then maybe you can give us a longer example of the JSON.

Edit: If none of this stuff works then I'm starting to think there might be something wrong with the syntax of your JSON.

Lamson answered 29/4, 2009 at 14:53 Comment(2)
I found the solution the hard way (not JQuery). I will try this out asap. I'd rather do it your way. I'll make sure to post the solution.Acetometer
So this very, very close. Now i am looping through the array of objects. In FireBug I can see the values in the properties but the alert just returns "Undefined". How can I get the string, dates, etc out of the properties?Acetometer
E
7
var d = $.parseJSON(result.d);
for(var i =0;i<d.length;i++){
    alert(d[i].EmployeeName);
}
Este answered 20/9, 2012 at 7:7 Comment(1)
here check the following link hope it helps encosia.com/never-worry-about-asp-net-ajaxs-d-againEste
A
4

This will work!

$(document).ready(function ()
    {
        $.ajax(
            {
            type: 'POST',
            url: "/Home/MethodName",
            success: function (data) {
                //data is the string that the method returns in a json format, but in string
                var jsonData = JSON.parse(data); //This converts the string to json

                for (var i = 0; i < jsonData.length; i++) //The json object has lenght
                {
                    var object = jsonData[i]; //You are in the current object
                    $('#olListId').append('<li class="someclass>' + object.Atributte  + '</li>'); //now you access the property.

                }

                /* JSON EXAMPLE
                [{ "Atributte": "value" }, 
                { "Atributte": "value" }, 
                { "Atributte": "value" }]
                */
            }
        });
    });

The main thing about this is using the property exactly the same as the attribute of the JSON key-value pair.

Ashmore answered 13/5, 2016 at 22:16 Comment(3)
How about that? I think now it's better explained.Ashmore
Better - without the yelling, as well. Good luck!Allomorphism
By the way, Sterling, your "someclass" is missing the close quote.Wolfort
L
2

I have the following call:

$('#select_box_id').change(function() {
        var action = $('#my_form').attr('action');
    $.get(action,{},function(response){
        $.each(response.result,function(i) {

            alert("key is: " + i + ", val is: " + response.result[i]);

        });
    }, 'json');
    });

The structure coming back from the server look like:

{"result":{"1":"waterskiing","2":"canoeing","18":"windsurfing"}}
Levi answered 23/11, 2010 at 10:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.