0

I'm using the Last.fm API to return data in JSON format and this works fine. I'm using the user.getTopArtist() API call.

As the page loads, a DIV object is created for each artist containing relevant details from the JSON data. When a user performs an action with the DIV I basically want to swap the image url to show a bigger image size!

How can I find/reference a JSON object by matching it's stored value?

For example, if I need to match the artist name 'Kate Bush' and then retrieve the "extralarge" image url. How would I do this?

The data structure looks like this:

{"topartists":{
  "artist":[{
    "name":"Kate Bush",
    "playcount":"20",
    "mbid":"4b585938-f271-45e2-b19a-91c634b5e396",
    "url":"http:\/\/www.last.fm\/music\/Kate+Bush",
    "image":[
      {"#text":"http:\/\/userserve-ak.last.fm\/serve\/34\/224740.jpg","size":"small"},
      {"#text":"http:\/\/userserve-ak.last.fm\/serve\/64\/224740.jpg","size":"medium"},
      {"#text":"http:\/\/userserve-ak.last.fm\/serve\/126\/224740.jpg","size":"large"},
      {"#text":"http:\/\/userserve-ak.last.fm\/serve\/252\/224740.jpg","size":"extralarge"},
      {"#text":"http:\/\/userserve-ak.last.fm\/serve\/500\/224740\/Kate+Bush.jpg","size":"mega"}
    ]
  }
}
walden
  • 135
  • 1
  • 5
  • I have spotted the pattern in the image URL, the first number corresponds to the pixel width, so manipulating the URL in this fashion (replacing the width) would achieve what I want but it seems a crude hack. – walden Mar 21 '11 at 21:08

2 Answers2

0

What are you using to parse JSON? Here's a jQuery example http://api.jquery.com/jQuery.parseJSON/

eagerMoose
  • 1,123
  • 5
  • 13
  • 35
  • Erm, good point. At the moment I don't think I am! I initially use getJSON() with a default callback function to iterate through using $.each(data.topartists.artist, function(i, item){ item.name;}). I then save the JSON request as a variable for referencing later. var topArtists = data.topartists; – walden Mar 21 '11 at 21:14
0

If it is just for this particular task then that $.each(data.topartists.artist[0].images) approach would work.

As of more generic solution... Take a look on http://goessner.net/articles/JsonPath/ - that is XPath variant for JSON

c-smile
  • 26,734
  • 7
  • 59
  • 86