April 27, 2012

Get JSON Data – newbie here

Question by redditor

I am using the Songkick API to list the next gig date, I have adapted the code found here. This is a copy of the JSON data source.

The HTML:

<head>
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.livequery.js" type="text/javascript"></script>
<script src="jquery.nano.js" type="text/javascript"></script>
<script src="application.js" type="text/javascript"></script>
</head>
<body>
<ul id="concerts">Loading Next Gig...</ul>
</body>

application.js is:

$(document).ready(function () {
  var template = "<li>Our next gig is <a href='{uri}'>{displayName}</a></li>";
  var apikey = 'MY_API_KEY';
  var container = $("ul#concerts");
  $.getJSON('http://api.songkick.com/api/3.0/artists/253846/calendar.json?apikey=' + apikey + '&jsoncallback=?', function(data) {
    container.html("");
    events = data["resultsPage"]["results"]['event'];
if (events==null) {
      container.append($.nano());
}
else {
      container.append($.nano(template, events[0]));
}
  });
});

I would like to display for the first listed gig only,

event.location.city
event.venue.displayName
event.start.date (in dd MMM format).

If no events are listed, I would like it say something like “There are currently no gigs booked at the moment, please [a href="example.com"] click here [/a] for up to date information.”

Answer by aSeptik

  var events = data.resultsPage.results.event;
  $.each(events, function (i, item) {
        container.append($.nano(template, item));
    });

NOTE: since you are using $.nano you should iterate over the json object in order to replace the shortcode inside the template var.

if you want to access the json properties singularly you should access it like below:

var uri = events.uri;
var displayName = events.displayName;

you full code will look like this:

$(document).ready(function () {
    var template = "<li>Our next gig is <a href='{uri}'>{displayName}</a></li>";
    var apikey = 'MY_API_KEY';
    var container = $("ul#concerts");
    $.getJSON('http://api.songkick.com/api/3.0/artists/253846/calendar.json?apikey=' + apikey + '&jsoncallback=?', function (data) {
        container.html("");
        var events = data.resultsPage.results.event;
        if (events !== null) {
      $.each(events, function (i, item) {
            container.append($.nano(template, item));
        });
        }
    });
});

Answer by Starx

Access the json tree with . (Dots)

events = data.resultsPage.results.event;

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!