2014-11-20 2 views
0

Я пишу просто одностраничное приложение для погоды, используя API Openweathermap, но я столкнулся с проблемой, проходящей через возвращаемые объекты вложенных объектов JSON.JSON для OpenWeatherMap API

Вот образец JSON:

"cod":"200", 
"message":0.1986, 
"city":{ 
    "id":"4781530", 
    "name":"Reston", 
    "coord":{ 
     "lon":-77.3545, 
     "lat":38.9597 
    }, 
    "country":"United States of America", 
    "population":0 
}, 
"cnt":2, 
"list":[ 
    { 
     "dt":1416499200, 
     "temp":{ 
      "day":45.3, 
      "min":33.48, 
      "max":52, 
      "night":34.47, 
      "eve":50.59, 
      "morn":33.48 
     }, 
     "pressure":1015.56, 
     "humidity":58, 
     "weather":[ 
      { 
       "id":801, 
       "main":"Clouds", 
       "description":"few clouds", 
       "icon":"02d" 
      } 
     ], 
     "speed":9.07, 
     "deg":212, 
     "clouds":24 
    }, 
    { 
     "dt":1416585600, 
     "temp":{ 
      "day":33.04, 
      "min":20.55, 
      "max":38.86, 
      "night":22.87, 
      "eve":38.03, 
      "morn":24.42 
     }, 
     "pressure":1027.28, 
     "humidity":50, 
     "weather":[ 
      { 
       "id":800, 
       "main":"Clear", 
       "description":"sky is clear", 
       "icon":"01d" 
      } 
     ], 
     "speed":7.99, 
     "deg":301, 
     "clouds":0 
    } 
] 

}

Я могу успешно перебрать первый набор значений в obj.list, но я получаю неопределенную ошибку, когда он достигает $.each(obj.list[i].weather[i], function(key,value) петля.

Как бы я прошел через вложенные объекты погоды и темпа, и почему мой текущий код дал мне неопределенную ошибку? Я включил код и журнал консоли Firebug. Любая помощь с благодарностью.

функция петли JQuery

$.each(obj.list, function(i) { 
    $.each(obj.list[i], function(key,value) { 

     if(typeof value == "object"){ 
      console.log(key + " is an Object!!"); 

      if(key=="weather"){ 
          console.log("What is i? " + i); 
          console.log(obj.list[i].weather[i]); 

          $.each(obj.list[i].weather[i], function(key,value) { 
            console.log("weather object " + key + ": " + value); 
          }); 
      } 

     } 
     else{ 
      console.log("outer object " + key + ": " + value); 
     } 
    }); 
}); 

Firebug журнал консоль:

outer object dt: 1416499200 
scripts.js (line 72) 
temp is an Object!! 
scripts.js (line 49) 
outer object pressure: 1015.56 
scripts.js (line 72) 
outer object humidity: 58 
scripts.js (line 72) 
weather is an Object!! 
scripts.js (line 49) 
What is i? 0 
scripts.js (line 59) 
Object { id=801, main="Clouds", description="few clouds", more...} 
scripts.js (line 60) 
weather object id: 801 
scripts.js (line 66) 
weather object main: Clouds 
scripts.js (line 66) 
weather object description: few clouds 
scripts.js (line 66) 
weather object icon: 02d 
scripts.js (line 66) 
outer object speed: 9.07 
scripts.js (line 72) 
outer object deg: 212 
scripts.js (line 72) 
outer object clouds: 24 
scripts.js (line 72) 
*********** 
scripts.js (line 103) 
outer object dt: 1416585600 
scripts.js (line 72) 
temp is an Object!! 
scripts.js (line 49) 
outer object pressure: 1027.28 
scripts.js (line 72) 
outer object humidity: 50 
scripts.js (line 72) 
weather is an Object!! 
scripts.js (line 49) 
What is i? 1 
scripts.js (line 59) 
undefined 

ответ

1

Вы просите только i го элемента из каждого obj.list[i].weather списка. Вы должны зациклиться на obj.list[i].weather, вместо того, чтобы запрашивать у него один элемент. Итак, для obj.list[0], вы запрашиваете только obj.list[0].weather[0]. Для obj.list[1] вы запрашиваете только obj.list[1].weather[1], которого нет (то, что weather имеет только один объект, с индексом 0).

Ваши $.each(obj.list[i].weather[i], ...) петли над obj.list[i].weather[i], но вы не перегибаете obj.list[i].weather. Вы хотите что-то с двумя переменными циклами, такими как obj.list[i].weather[j], а не obj.list[i].weather[i].

if(typeof value == "object"){ 
     console.log(key + " is an Object!!"); 

     if(key=="weather"){ 
       console.log("What is i? " + i); 

       $.each(obj.list[i].weather, function(j) { 
        console.log(obj.list[i].weather[j]); 
        $.each(obj.list[i].weather[j], function(key,value) { 
         console.log("weather object " + key + ": " + value); 
        }); 
       }); 
     } 

    } 

Здесь мы добавим петлю над obj.list[i].weather с внутренним переменным прыгающим способом j так, что мы получаем все элементы в каждом weather списке, а не только один ..

Смежные вопросы