【问题标题】:get specific value from json file by Id通过 Id 从 json 文件中获取特定值
【发布时间】:2014-11-20 09:37:24
【问题描述】:

我正在使用 $.get 获取运行良好的 JSON 文件内容,目前我想过滤并获取 ID 为 4(最后一个)的项目,我应该怎么做? 在 Jquery 文档中我没有找到一些提示...... http://api.jquery.com/jquery.get/

这是代码:

 $.get('tweets.json');

这是 JSON 文件内容

[
  {
   "id": 1,
   "tweet": "OMG, worst day ever, my BF @BobbyBoo dumped me",
   "usersMentioned": [
     {
      "id": 10,
      "username": "BobbyBoo"
     }
    ]
  },
  {
   "id": 2,
   "tweet": "OMG, best day ever, my BF came back to me"
  },
  {
   "id": 3,
   "tweet": "OMG, worst day ever, just don't ask"
  },
  {
   "id": 4,
   "tweet": "@BobbyBoo OMG...just OMG!",
   "usersMentioned": [
     {
      "id": 10,
      "username": "BobbyBoo"
     }
    ]
  }
]

更新

当前,当我尝试以下操作时,我在 then(function (tweets) 中没有得到任何东西,tweets 是 emtpy 值 entry4 填充了正确的值...

  $.get('profile.json').then(function (profile) {

    $('#profile-pre').html(JSON.stringify(profile));

     $.get('tweets.json', null, null, 'json')
        .then(function (response) {
           var entry4 =  response.filter(function (tweet) {
               return tweet.id === 4;
            })[0];
             return entry4 ;
        })



}).then(function (tweets) {

    $('#tweets-pre').html(JSON.stringify(tweets));

    var myFriend = $.get('friend.json');

    return myFriend
}).then(function (friend) {

【问题讨论】:

    标签: javascript jquery json promise


    【解决方案1】:

    那就是

    $.get('tweets.json',null,null,'json')
      .then(function(response){
        var iAmNumberFour = response.filter(function(tweet){
          return tweet.id === 4;
        })[0];
      });
    

    添加类型,因为如果您不传递正确的标头,jQuery 将不会为您解析 JSON。


    $.get('profile.json').then(function(profile) {
    
      $('#profile-pre').html(JSON.stringify(profile));
    
      return $.get('tweets.json', null, null, 'json')
        .then(function(response) {
          var entry4 = response.filter(function(tweet) {
            return tweet.id === 4;
          })[0];
          return entry4;
        })
    
    }).then(function(entry4) {
    
      $('#tweets-pre').html(JSON.stringify(tweets));
    
      var myFriend = $.get('friend.json');
    
      return myFriend
    })
    

    【讨论】:

    • @A.Wolff 这也有效 :D 但我发现$.get 更容易记住。
    • 我发现$.getJSON() 更具可读性,无论如何 +1 为这个正确答案 :=)
    • @JosephtheDreamer-thanks,投了赞成票,请看我的更新,因为我已经使用了 promise 我没有得到任何东西(函数(推文){,任何想法
    • 是的,使用返回值return iAmNumberFour
    • @AlBundy @AlBundy then 的一个魔术技巧是,当您在其中返回一个 Promise 时,下一个链接的 then 会得到它解决的任何问题。如果你在内部获取return $.get(...),然后'ed return entry4,那么你将在你的第一个AJAX调用的链接then中得到entry4。如果你不这样做,那么链接的then 会改为profile
    猜你喜欢
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    相关资源
    最近更新 更多