Search code examples
javascriptjqueryjsongetjson

Accessing more complex JSON with jQuery


I am trying to access this data from a JSON file I have created:

{
  "game":"one",
  "schedule":[
    {
      "day":"mon",
      "start":"00:00:00",
      "end":"05:30:00"
    },
    {
      "day":"tue",
      "start":"00:00:00",
      "end":"05:30:00"
    }
  ],
  "game":"two",
  "schedule":[
    {
      "day":"mon",
      "start":"00:00:00",
      "end":"05:30:00"
    },
    {
      "day":"wed",
      "start":"00:00:00",
      "end":"05:30:00"
    }
  ],
  "game":"three",
  "schedule":[
    {
      "day":"fri",
      "start":"00:00:00",
      "end":"05:30:00"
    },
    {
      "day":"thu",
      "start":"00:00:00",
      "end":"05:30:00"
    }
  ]
}

This is how I am trying to access it:

  $.getJSON(json_location, function(data) {
    $.each(data.schedule, function() {
      console.log(this.day + " " + this.start + " " + this.end);
    });
  });

However this only returns the values within game three - so: fri 00:00:00 05:30:00, thu 00:00:00 05:30:00. Ideally I want to be able to iterate through game one, then two, then three. However regardless of how much I try to adapt my code I cannot allow $.getJSON to access the data.

I am also aware that this format is valid to use with javascript, however not valid according to RFC 4627 (JSON specification) - so any suggestions on how to improve the layout of the JSON would be greatly appreciated.


Solution

  • You are right, this JSON is wrong since there are multiple values for the same keys game and schedule

    try something like this (simplest change)

    {
      "one":[
        {
          "day":"mon",
          "start":"00:00:00",
          "end":"05:30:00"
        },
        {
          "day":"tue",
          "start":"00:00:00",
          "end":"05:30:00"
        }
      ],
      "two":[
        {
          "day":"mon",
          "start":"00:00:00",
          "end":"05:30:00"
        },
        {
          "day":"wed",
          "start":"00:00:00",
          "end":"05:30:00"
        }
      ],
      "three":[
        {
          "day":"fri",
          "start":"00:00:00",
          "end":"05:30:00"
        },
        {
          "day":"thu",
          "start":"00:00:00",
          "end":"05:30:00"
        }
      ]
    }
    

    then iterate it like

    for ( var gameId in data )
    {
       var scheduleArray = data[ gameId ];
    //iterate this array
    }