在JSON输出中选择特定数据

时间:2015-09-01 12:57:12

标签: json angularjs

我创建了一个执行http请求的函数,然后从JSON输出中保存了一些数据。

$scope.addMovie = function() {

  'http://api.themoviedb.org/3/movie/206647?api_key=a8f7039633f2065942cd8a28d7cadad4&append_to_response=releases'
  // Search for release dates using the ID.
  var base = 'http://api.themoviedb.org/3/movie/';
  var movieID = $(event.currentTarget).parent().find('.movieID').text()
  var apiKey = 'a8f7039633f2065942cd8a28d7cadad4&query='
  var append_to_response = '&append_to_response=releases'
  var callback = 'JSON_CALLBACK'; // provided by angular.js
  var url = base + movieID + '?api_key=' + apiKey + append_to_response + '&callback=' + callback;

  $http.jsonp(url,{ cache: true}).
    success(function(data, status, headers, config) {

      if (status == 200) {
          // $scope.movieListID = data.results;
          $scope.movieListID = data;
          console.log($scope.movieListID);

          createMovie.create({
            title: $scope.movieListID.original_title,
            release_date: $scope.movieListID.release_date,
            image: $scope.movieListID.poster_path
          }).then(init);

      } else {
          console.error('Error happened while getting the movie list.')
      }
    })
};

此功能保存标题,发布日期和海报路径,并且工作正常。问题是它只保存一个release_date而JSON输出有更多,但我不知道如何访问它。

This is a example of the JSON output I request

它有release_date,我现在保存,但它还有更多信息,

releases":{
  "countries":[
    {"certification":"","iso_3166_1":"GB","primary":true,"release_date":"2015-10-26"},
    {"certification":"","iso_3166_1":"US","primary":false,"release_date":"2015-11-06"},
    {"certification":"","iso_3166_1":"NL","primary":false,"release_date":"2015-11-05"},
    {"certification":"","iso_3166_1":"BR","primary":false,"release_date":"2015-11-05"},
    {"certification":"","iso_3166_1":"SE","primary":false,"release_date":"2015-11-04"},
    {"certification":"","iso_3166_1":"IE","primary":false,"release_date":"2015-10-26"},

我如何保存NL版本的发布日期?

1 个答案:

答案 0 :(得分:1)

您只需遍历countries数组,并检查国家/地区代码是否与您要检索的国家/地区代码匹配。对于'NL'的例子:

var releaseNL;
for (var i = 0; i < $scope.movieList.releases.countries.length; i++) {
    var release = $scope.movieList.releases.countries[i];        
    if (release['iso_3166_1'] == 'NL') {
        releaseNL = release;
    }
}

这只是执行此操作的众多方法之一(例如,您可以使用angular.forEach,将其包装在函数内等),但这应该会给您一个想法。

备注:我注意到你今天提出了很多非常基本的问题,你可以通过更多的研究轻松回答这些问题。例如。这个问题甚至与AngularJS无关,只是一个简单的JavaScript任务。所以也许下次尝试展示一点主动权! ;)