从API请求引用JSON数据结果 - Javascript

时间:2017-09-30 07:24:56

标签: javascript json

我首先要说的是我是一个非常新的网络开发人员,所以如果这是过于基本的话我会道歉......我在谷歌的任何地方都找不到它。我正在从对omdb的API调用中收到JSON数据,我不确定如何在数据中引用一行。具体来说,我正在尝试引用烂番茄值,这对于我搜索的任何电影都需要可重复。我首先将响应存储在JSON中,然后处理我需要的每个项目:

var body = JSON.parse(body);
console.log("Title: " + body.Title);
console.log("Release Year: " + body.Year);
console.log("IMdB Rating: " + body.imdbRating);
console.log("Country: " + body.Country);
console.log("Language: " + body.Language);
console.log("Plot: " + body.Plot);
console.log("Actors: " + body.Actors);
console.log("Rotten Tomatoes Rating: " + body.Ratings.????RottenTomatoes???);

这只是腐烂的西红柿价值线,我无法弄清楚!其他一切都有效。为了澄清,这只是一个我无法弄清楚的JSON引用问题。

{
  "Title": "Anastasia",
  "Year": "1997",
  "Rated": "G",
  "Released": "21 Nov 1997",
  "Runtime": "94 min",
  "Genre": "Animation, Adventure, Drama",
  "Director": "Don Bluth, Gary Goldman",
  "Writer": "Susan Gauthier (screenplay), Bruce Graham (screenplay), Bob Tzudiker (screenplay), Noni White (screenplay), Eric Tuchman (animation adaptation)",
  "Actors": "Meg Ryan, John Cusack, Kelsey Grammer, Christopher Lloyd",
  "Plot": "The last surviving child of the Russian Royal Family joins two con men to reunite with her grandmother, the Dowager Empress, while the undead Rasputin seeks her death.",
  "Language": "English, Russian, French",
  "Country": "USA",
  "Awards": "Nominated for 2 Oscars. Another 10 wins & 21 nominations.",
  "Poster": "https:\/\/images-na.ssl-images-amazon.com\/images\/M\/MV5BNGJiNWFlYTMtZTBiZi00ZTVmLWJmZmMtNzEzYzZjNzYzZmRmXkEyXkFqcGdeQXVyNTA4NzY1MzY@._V1_SX300.jpg",
  "Ratings": [
    {
      "Source": "Internet Movie Database",
      "Value": "7.1\/10"
    },
    {
      "Source": "Rotten Tomatoes",
      "Value": "85%"
    },
    {
      "Source": "Metacritic",
      "Value": "59\/100"
    }
  ],
  "Metascore": "59",
  "imdbRating": "7.1",
  "imdbVotes": "94,074",
  "imdbID": "tt0118617",
  "Type": "movie",
  "DVD": "16 Nov 1999",
  "BoxOffice": "N\/A",
  "Production": "20th Century Fox",
  "Website": "N\/A",
  "Response": "True"
}

3 个答案:

答案 0 :(得分:1)

Rotten tomatoes值位于数组的第3个元素中。数组索引从0开始。因此,您需要的是body.Ratings[2].Value

答案 1 :(得分:1)

如果Ratings array的顺序无法预测,请使用filter功能,如下所示。

    //If the order of the source array is unpredictable
    //use filter

    var rtValue = body.Ratings.filter(function(source) {
      return source.Source === "Rotten Tomatoes";
    }).Value;

答案 2 :(得分:0)

那是因为它是一个对象内的数组。 body.Ratings [0]。您正在引用数组的位置。绝对要看数组。

 "Ratings": [ { "Source": "Internet Movie Database", "Value": "7.1/10" }, { "Source": "Rotten Tomatoes", "Value": "85%" }, { "Source": "Metacritic", "Value": "59/100" } ]

参见[方括号] {}内的每个对象都可以用[0],[1]等内的整数引用。 看一些在线教程。 www.w3schools.com/js是一个很好的起点