How to iterate over JSON array?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • BaseballGraphs
    New Member
    • Sep 2010
    • 75

    How to iterate over JSON array?

    Hello,

    I am trying to iterate over a JSON array using JQuery's .getJSON method and am requiring assistance building the javascript function to iterate and return all values in my array.

    My JSON array takes the following form:
    Code:
    {
      -49: {
        -1: {
             value: "6.0366"
             name: "D. Aardsma"
             }
        -2: {
             value: "7.8261"
             name: "F. Abad"
             }
    
    // Lots more information
    
        -1438: {
              value: "7.5591"
              name: "J. Zumaya"
              }
            }
          }
    Ultimately, I want to return all of the values in this array in a list.

    Here is the function I have built so far:
    Code:
    function refreshRankings( stat_id ) {
    var url = "/pullrankings.php?s=" + stat_id + "";
    $.getJSON( url,
       function(data){
         for ( statistic_id in data ) {
            for ( player_id in data[ statistic_id ] ) {
              for ( value in data[ statistic_id ][ player_id ] ) {
                RankPlayers ( data[ statistic_id ][ player_id ].value );
             }
            }
           }
          } );
    I'm finding that when I output RankPlayers, I am only outputting the final value in the array.

    Here is how I output the array:
    Code:
    var RankPlayers = function(array) {
    var div = $('<div id="rankings">'+ array +'</div>');
    $('#rankings').replaceWith( div );
     }
    }
    If you know how I can alter my function to accomplish iterating over all the values in my JSON array I would very grateful!

    Thanks very much.
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    Try using $.each to iterate over the array.

    Comment

    Working...