使用 JS/AJAX (Last.fm) 在 JSON 对象中搜索特定值
我使用 Last.fm API 以 JSON 格式 返回数据,效果很好。我正在使用 user.getTopArtist() API 调用。
页面加载时,将为每个艺术家创建一个 DIV 对象,其中包含 JSON 数据的相关详细信息。当用户使用 DIV 执行操作时,我基本上想交换图像 url 以显示更大的图像尺寸!
如何通过匹配 JSON 对象的存储值来查找/引用它?
例如,如果我需要匹配艺术家姓名“Kate Bush”,然后检索“超大”图像网址。我该怎么做?
数据结构如下所示:
{"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"}
]
}
}
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"}
]
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你用什么来解析 JSON?
这是一个 jQuery 示例 http://api.jquery.com/jQuery.parseJSON/
What are you using to parse JSON?
Here's a jQuery example http://api.jquery.com/jQuery.parseJSON/
如果只是为了这个特定的任务,那么
$.each(data.topartists.artist[0].images)
方法就可以工作。至于更通用的解决方案......看看 http://goessner.net/articles/JsonPath/ - 这是 JSON 的 XPath 变体
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