从JSON数组中检索数据

时间:2015-02-10 20:37:55

标签: javascript arrays json bit.ly

我试图从bit.ly API返回的json数组中获取值

回复是:

{"status_code": 200, "data": {"bundle": {"og_image": null, "bundle_owner": "user", "created_ts": 1423596727, "description": "", "links": [{"updated_by": null, "title": "", "display_order": 0, "lm": 1423597992.378417, "ts": 1423597992.378417, "comments": [], "aggregate_link": "http://bit.ly/LmvF", "long_url": "http://google.com/", "link": "http://bit.ly/1AUeg5k", "preview": 1, "added_by": "rentthesun"}], "title": "Barcelona 226", "collab": [], "private": true, "inv_collab": [], "last_modified_ts": 1423597992, "bundle_link": "http://bitly.com/bundles/myuser/2", "preview": true}}, "status_txt": "OK"}

我想获得" link"

的价值

我的代码:

$.getJSON("https://api-ssl.bitly.com/v3/bundle/link_add?", {
     "access_token": "MY_TOKEN",
      "bundle_link": "https://bitly.com/bundles/user/2",
      "link": raw_url,
 }, function(response) {
       $("#link-container").show("fast");
       link = "<a href=\"" + response.data['bundle']['links'].link[0] + "\" target=\"_blank\">" + response['data']['bundle']['links'].link[0] + "</a>";
       $("#link").html(link);
 });

如何获得缩短的链接?

1 个答案:

答案 0 :(得分:0)

link = "<a href=\"" + response.data['bundle']['links'].link[0] + "\" target=\"_blank\">" + response['data']['bundle']['links'].link[0] + "</a>";

我认为你的意思是 response['data']['bundle']['links'][0].link 。这将选择第一个元素的链接,而原始代码正在查找link数组的第一个元素。

如果你总是需要它作为最后一个链接,最简单的方法是保存链接数组,并获取它的最后一个元素:

links = response.data['bundle']['links'];
link = "<a href=\"" + links[links.length-1].link + "\" target=\"_blank\">" + links[links.length-1].link + "</a>";