0

In the following JSON data, I want to access 'lon' and 'lat' in 'coord'. I know data.coord would give me [ 'lon', 'lat' ], but how can I get the values belonging to each?

Here's my JSON data:

var data = {
    "coord": {
        "lon": 159,
        "lat": 35
    },
    ...
};
Omar Einea
  • 2,478
  • 7
  • 23
  • 35
user2763557
  • 449
  • 5
  • 18

3 Answers3

1

You could accesss them like this:

var 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 };

console.log('Lon',data.coord.lon);
console.log('Lat',data.coord.lat);

//Also you can do that using object destructuring in es6 like this:

var {lon,lat} = data.coord;
console.log('Lon',lon);
console.log('Lat',lat);

Checkout MDN for more about objects and properties: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

Check out Object destructuring

Manos Kounelakis
  • 2,848
  • 5
  • 31
  • 55
1

data.coord won't give you [ 'lon', 'lat' ] array, rather it would give you { "lon": 159,"lat": 35 } object.

You can get their values just like you would get value of any object like: data.coord.lat and data.coord.lon

So something like var latitude = data.coord.lat; var longitude = data.coord.lon

EDIT:

Similarly, for weather you can access weather using data.weather, however thing to note is that weather is an array. So, you can get hold of 1st element using index=0.

Effectively, you'll write, var myWeatherObject = data.weather[0]; //0 is index of 1st element

Again, to access individual weather properties, you can use: myWeatherObject.id, myWeatherObject.main, myWeatherObject.description and myWeatherObject.icon

Aniket Sinha
  • 6,001
  • 6
  • 37
  • 50
  • what about weather? how do i access that? – user2763557 Mar 18 '18 at 14:29
  • JSON provided in question doesn't has any `weather` key, so I'm assuming it'll be present. You can access weather the same way you access any key in JSON. e.g `data.weather`. Post full JSON for details. – Aniket Sinha Mar 18 '18 at 16:06
0

You can also access the values with this syntax data['coord']. With this syntax you can run through the json file searching for a corresponding key.

for(let key in json) {
 if(key==='coord'){
//do stuff
  }
}
jimas13
  • 597
  • 5
  • 19