0

i just started with lastfm and json. i can get the information i want to return object values in the console, but i can't figure out why i keep getting a value of "undefined". here's all my code. thanks!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>
<head>
    <title>JSON LastFM API Test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
        $.getJSON("http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&artist=Bjork&api_key=690e1ed3bc00bc91804cd8f7fe5ed6d4&format=json&callback=?", function(data) {
            var html = '';
            $.each(data.artist, function(i, item) {
                html += "<p>" + item.name + "</p>";
                console.log(data);
            });
            $('#test').append(html);
        });

    </script>

    <div id="test"></div>
</body>

heyjohnmurray
  • 205
  • 3
  • 14

2 Answers2

1

It appears the JSON returned is not an array.

Perhaps you can try

$.getJSON("http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&artist=Bjork&api_key="+ apikey+"&format=json&callback=?", function(data) {
        $('#test').append("<p>" + data.artist.name + "</p>");
});
ironchefpython
  • 3,409
  • 1
  • 19
  • 32
  • thanks ironchefpython. what you wrote worked, but i kept going. using what you wrote helped me figure out how to write mine in the context i needed it. i ended up writing $.getJSON("http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&artist=Bjork&api_key=0bd6c5780da878f5bb51393e84329809&format=json&callback=?", function(data) { var html = ''; $.each(data, function(i, item) { html += "

    " + data.artist.name + "

    "; console.log(data); }); $('#test').append(html); });
    – heyjohnmurray Feb 13 '12 at 05:05
  • Your `$.each` in that context is superfluous, as there's only a single property of `data`. – ironchefpython Feb 13 '12 at 05:09
0

If it's just the name you want to have it is pretty simple in this case:

   $.each(data, function(i, item) {
        html += "<p>" + item.name + "</p>";
        html += "<p>" + item.url + "</p>";
        console.log(data);
    });
    $('#test').append(html);

Please provide me with a more complex context, so I can help you have that.

Johannes Staehlin
  • 3,680
  • 7
  • 36
  • 50