开发者

Search JSON objects for a specific value with JS/AJAX (Last.fm)

开发者 https://www.devze.com 2023-02-18 01:17 出处:网络
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.

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"开发者_StackOverflow,
    "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"}
    ]
  }
}


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消