How can I break down this long string returned by the openweathermap API?

Viewed 46

Hey everyone!

So, recently I wanted to learn how to use an API and I figured the openweathermap API could be really fun. I successfully got the API request returning a value, but in its' current state it's unusable. Does anyone know how I can split this string appart to set each value here as a variable?

Here's the call I am using:

var request = new XMLHttpRequest();
request.open('GET', 'http://api.openweathermap.org/data/2.5/weather?q={not a real city}&appid={censored}', true); //not a real id
request.onload = function() {
    console.log(request.response);
}
request.send();

And the response I need to try and use looks something like:

{"coord":{"lon":-85.4898,"lat":42.9595},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"base":"stations","main":{"temp":267.51,"feels_like":262.69,"temp_min":265.93,"temp_max":269.26,"pressure":1026,"humidity":74},"visibility":10000,"wind":{"speed":2.57,"deg":270},"clouds":{"all":1},"dt":1615029875,"sys":{"type":1,"id":4269,"country":"US","sunrise":1615032556,"sunset":1615073839},"timezone":-18000,"id":4993125,"name":"Forest Hills","cod":200}

So yea, that ^^ is what I need to try to break-down. I could use string.split() a bunch of times, but that seems really messy to me. I feel like there has to be a better way that I don't know about. I know this is probably really easy but, again, this is my first time using any API. I also tried searching the internet (and here on Stack) for an answer but couldn't find one.

Thanks!

1 Answers

As @JoshG mentionned, you can use JSON.parse(...) to parse any JSON-string into a javascript object.

An alternative would be to replace your current use of the older XMLHttpRequest api (which has a kind of messy API) with the newer fetch api (which is easier).

For example:

fetch('http://api.openweathermap.org/data/2.5/weather?q={not a real city}&appid={censored}')
  .then(res => res.json())
  .then(function(res) {
    console.log(res);
  });

Related