how to parse json array

Arrays and objects are different things. You will want to investigate them tons more before things get really challenging.

Assuming json really does equal the object you provide (in JSON those show up as {}), then json['popular result'] (you could use a . if there wasn’t a space) is the array (in JSON those show up at []) you want to traverse.

For some reason, this confusion got you looping over an object (not going to get you anywhere as length is rarely defined for it) and then (ignoring the typo on myJson), you started looping over something that didn’t exist (which didn’t crash b/c it never got there).

Cleaning it up…

<script type="text/javascript">
    $(document).ready(function () {
        $.getJSON('/Controls/GetPopularSearches', function (json) {
            for (var i=0;i<json['popular result'].length;i++) {
                alert(json['popular result'][i].term + ' points to the URL ' + json['popular result'][i].url);
            }
        });
    });
</script>

Notice how the alert references the json object (that’s your variable name), the popular result array, then [i] is the “row” in that array, and the term/url element of the object on that row.

NOTE: Running something with a ton of alerts as you’re debugging is annoying. Check out console.log.

Leave a Comment