Javascript jQuery从API获取JSON如何访问对象?

Javascript jQuery从API获取JSON如何访问对象?,javascript,jquery,json,ajax,Javascript,Jquery,Json,Ajax,我试图从API获取JSON,然后访问JSON的“weather”对象的“main”对象 当我使用此代码时: $.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139", function(json) { var data = JSON.stringify(json); alert(data); }); 我得到这个输出: { "coord": { "lon": 159, "l

我试图从API获取JSON,然后访问JSON的
“weather”
对象的
“main”
对象

当我使用此代码时:

$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139", function(json) {
  var data = JSON.stringify(json);
  alert(data);
});
我得到这个输出:

{
  "coord": {
    "lon": 159,
    "lat": 35
  },
  "weather": [{
    "id": 500,
    "main": "Rain",
    "description": "light rain",
    "icon": "https://cdn.glitch.com/6e8889e5-7a72-48f0-a061-863548450de5%2F10n.png?1499366021399"
  }],
  "base": "stations",
  "main": {
    "temp": 22.59,
    "pressure": 1027.45,
    "humidity": 100,
    "temp_min": 22.59,
    "temp_max": 22.59,
    "sea_level": 1027.47,
    "grnd_level": 1027.45
  },
  "wind": {
    "speed": 8.12,
    "deg": 246.503
  },
  "rain": {
    "3h": 0.45
  },
  "clouds": {
    "all": 92
  },
  "dt": 1499521932,
  "sys": {
    "message": 0.0034,
    "sunrise": 1499451436,
    "sunset": 1499503246
  },
  "id": 0,
  "name": "",
  "cod": 200
}
现在,我试图得到的输出是
“Rain”
“weather”
对象的
“main”
对象的属性)(我希望我说得对,我是初学者)

所以从逻辑上讲,我会这样做:

$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139", function(json) {
  var data = JSON.stringify(json);
  alert(data["weather"].main);
});
但这并没有给我任何输出

我做了一些搜索,发现我应该解析

但当我这么做的时候:

$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139", function(json) {
  var data = JSON.stringify(json);
  var Jason = JSON.parse(data);
  alert(Jason["weather"].main);
});
我再次将
未定义的
作为输出

那么,我的代码应该是什么样的,这样我的输出就会是
“Rain”


PS:如果我在描述我的问题时犯了错误,很抱歉,我对JavaScript/jQuery非常陌生,而且英语是我的第二语言。

JSON。Stringify
将JSON转换为字符串。如果要访问对象,需要的是JSON对象,而不是字符串

天气是一个对象数组,您需要使用索引访问数组。当您想要第一个对象时,请使用json[“天气”][0]

$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139", function(json){
  alert(json["weather"][0].main);
});

在访问天气后,只需添加
[0]
即可。 由于weather是一个数组,因此需要使用该数组从第一个元素获取数据:

$.getJSON(“https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139", 
json=>console.log(json.weather[0].main)
);

如果你想访问对象的某些部分,就不要对对象进行字符串化。你能试试alert(json[“weather”])吗?为什么不在FCC论坛上问这个问题?@JohnnyBizzle因为这不是FCC的问题,而是对数组工作方式的误解,我想这个论坛更活跃/有用。另外,由于这个问题与FCC无关,但适用于jQuery的一般用法,我不明白为什么我不应该在这里问这个问题。小问题。为什么会有额外的局部变量?请在答案中添加一些解释。@DannyFardyJhonstonBermúdez刚刚补充道。谢谢。实际上不需要那个变量。