简体   繁体   中英

Correctly looping through a multi-dimensional JSON object with jQuery (AJAX)?

I've got a rather large JSON object that comes out looking like this:

[
    {
        "FoodNumber":"95809548",
        "FoodIdentification":"Food Name",
        "StockCode":"710",
        "Description":
        [
            "Blah blah blah",
            "More blah blah blah"
        ]
    },
    {
        "FoodNumber":"95892541",
        "FoodIdentification":"Another food name",
        "StockCode":"710",
        "Description":
        [
            "Food description here",
            "Additional description here"
        ]
    },
    {
        "FoodNumber":"97179370",
        "FoodIdentification":"Yet another food name",
        "StockCode":"602",
        "Description":[]
    },
    {
        "FoodNumber":"97270901",
        "FoodIdentification":"HEY",
        "StockCode":"602",
        "Description":[]
    }
]

As you can see, sometimes the description is empty, and sometimes it has more than one item. My current jQuery code is as follows:

        $("#SearchQueryButton").click(function () {
            $.ajax({
                url: "TestMe.aspx/PopulateMainTable",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({
                    min: 1,
                    max: 25,
                    searchQuery: $("#SearchQueryTextbox").val()
                }),
                dataType: "json",
                beforeSend: function (html) {
                    $('#initial_results').html('');
                },
                success: function (html) {
                    //console.log(html);
                    $.each(html.d, function (i, obj) {
                        console.log(obj);
                    });
                    //$('#initial_results').append(html);
                }
            });
        });
    });

If I replace " console.log(obj); " with any of the following lines:

1) console.log(html[i].FoodNumber);
2) console.log(obj.FoodNumber);

I get the same exact error as if I were using console.log(obj); :

Uncaught TypeError: Cannot use 'in' operator to search for '4579' in <insert giant blob of json here>    

I've tried a JSON validator to determine if it was a valid blob, and it is. I'm using the exact same JSON blob as I listed above, but with the description text removed. How do I correctly parse this? It's a rather large JSON string, about 4.52 KB in size, and I'm having trouble parsing it so I can display it to the user.

Thanks!

Finally, after debugging for a while, I found the solution to every problem I was having:

1) The string needs to be converted to json using $.parseJSON(zd);

var json = $.parseJSON(z.d);

2) I need " return false; " before the end of the function so it doesn't refresh and lose everything (note that initial_results is no longer an id, but a class).

Now I have everything I need. Full code below:

        $("#SearchQueryButton").click(function () {
            $.ajax({
                url: "TestMe.aspx/PopulateMainTable",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({
                    min: 1,
                    max: 25,
                    searchQuery: $("#SearchQueryTextbox").val()
                }),
                dataType: "json",
                beforeSend: function (html) {
                    $('.initial_results').html('');
                },
                success: function (z) {
                    var json = $.parseJSON(z.d);

                    $.each(json, function (i, obj) {
                        console.log(obj);
                    });
                },
                error: function(e)
                {
                    $('.initial_results').html("Error:" + e.toString());
                }
            });
            return false;
        });
    });

In json you can simply use the this to access the property like so :

$.each(html.d, function () {
    console.log(this.FoodNumber);
});

Are you sure the array is in html.d ? We don't have the server side code here.

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