【问题标题】:Search JSON objects for a specific value with JS/AJAX (Last.fm)使用 JS/AJAX (Last.fm) 在 JSON 对象中搜索特定值
【发布时间】:2011-03-21 21:04:36
【问题描述】:

我正在使用 Last.fm API 在JSON format 中返回数据,这工作正常。我正在使用user.getTopArtist() API 调用。

当页面加载时,会为每个艺术家创建一个 DIV 对象,其中包含来自 JSON 数据的相关详细信息。当用户使用 DIV 执行操作时,我基本上想交换图像 url 以显示更大的图像尺寸!

如何通过匹配存储的值来查找/引用 JSON 对象?

例如,如果我需要匹配艺术家姓名“Kate Bush”,然后检索“超大”图像 url。我该怎么做?

数据结构如下:

{"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"}
    ]
  }
}

【问题讨论】:

  • 我在图像 URL 中发现了模式,第一个数字对应于像素宽度,因此以这种方式操作 URL(替换宽度)可以达到我想要的效果,但这似乎是一个粗略的 hack .

标签: json last.fm


【解决方案1】:

你用什么来解析 JSON? 这是一个 jQuery 示例http://api.jquery.com/jQuery.parseJSON/

【讨论】:

  • 呃,好点。目前我认为我不是!我最初使用带有默认回调函数的 getJSON() 来迭代使用 $.each(data.topartists.artist, function(i, item){ item.name;})。然后我将 JSON 请求保存为变量以供以后引用。 var topArtists = data.topartists;
【解决方案2】:

如果只是为了这个特定的任务,那么$.each(data.topartists.artist[0].images) 方法会起作用。

作为更通用的解决方案...看看http://goessner.net/articles/JsonPath/ - 这是 JSON 的 XPath 变体

【讨论】:

    猜你喜欢
    • 2012-02-25
    • 1970-01-01
    • 2012-10-30
    • 2011-11-26
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    相关资源
    最近更新 更多