Mellroy
Mellroy

Reputation: 17

Get json object with jquery without using the $.each

I want to retrieve the status of the first track

"@attr":{"nowplaying":"true"}

I have this code to retrieve information about each track

$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=melroymusic&api_key=690e1ed3bc00bc91804cd8f7fe5ed6d4&limit=3&format=json&callback=?",

function(data){
    $.each(data.recenttracks.track, function(i,item){
    $("#lastfmMenu").append("<div class='lastfmItem'><div class='lastfmText'>"+item.artist['#text']+"</div>" + "<div class='lastfmDate'>"+item.name+"</div></div>");
    });
});

to retrieve the nowplaying status of the first track, logically I would do

$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=melroymusic&api_key=690e1ed3bc00bc91804cd8f7fe5ed6d4&limit=3&format=json&callback=?",

function(data){
    if (data.recenttracks.track[0]['@attr'].nowplaying == true){
        $("#lastfmMenu").append("Now Playing");
    }
    else {
        $("#lastfmMenu").append("Just played");
    }
});

doesn't give me any results.

Hope you can help me out.

Upvotes: 0

Views: 1537

Answers (2)

labroo
labroo

Reputation: 2961

did you try to parse it first? Try this (untested),

function(data){
  **var parsedData = $.parseJSON(data)**
    if (parsedData.recenttracks.track[0]['@attr'].nowplaying == true){
      $("#lastfmMenu").append("Now Playing");
    }
    else {
      $("#lastfmMenu").append("Just played");
    }
});

Upvotes: 0

DavidGouge
DavidGouge

Reputation: 4623

Is it because nowplaying is a string not a bool, so it should be

.nowplaying == "true"?

Not at a pc so I can't check.

Upvotes: 2

Related Questions