1

I know this question gets asked in different ways but I am struggling to wrap my head around how to handle the data returned from an API URI and hoping to get a clearer idea of how to properly use it.

I am practicing APIs and decided to make a simple weather app that gets data from openweathermap.com

An example URI is http://api.openweathermap.org/data/2.5/weather?q=Los+Angeles&APPID=myApiKey

I concat this data using an input on my page that fills in whatever city or zip you type in and printing the full path as a link works just fine. But when I try to parse the data from this URI I get an error

Uncaught SyntaxError: Unexpected token h in JSON at position 0
    at JSON.parse (<anonymous>)
    at getWeather (index.js:25)
    at HTMLButtonElement.onclick 

I am trying to break down the data inside of this API data so I can appropriately display things like temp, wind, humidity etc.

This is the code that I wrote to test if I am properly getting the data.

// Set API variables
const api = "http://api.openweathermap.org/data/2.5/weather?q=";
const apiKey ="myAPIKey";

// Set City and Units
let unitType = "imperial";
let units = "&units=" + unitType;

function setup() {
  var button = document.getElementById('submit');
  button.click = getWeather();
}


function getWeather() {
  let city = document.getElementById('city').value;
  let fullPath = api + city + "&APPID=" + apiKey + units;

  console.log(city);
  //document.getElementById('weatherData').innerHTML='<a href="' + fullPath + '">' + city + '</a>';

  let data = fullPath;
  let obj = JSON.parse(data);
  document.getElementById('weatherData').innerHTML = obj.main.temp;
}

the getWeather() function is called when you click the submit button on the page which looks like:

<!doctype html>
<html>
  <head></head>
  <body>
    <input type="text" id="city" placeholder="Enter a city" />
    <button onclick="getWeather()" id="submit">Submit</button>
    <div id="weatherData" style="background: #ccc; padding: 20px; margin-top: 25px;">
    </div>


    <script src="index.js"></script>
  </body>
</html>

What am I doing wrong? I have never worked with APIs before so please forgive me if I look very ignorant here. When I had the program just print a concatenated URL (linking to the URI itself) on the screen it worked, but now that I'm trying to actually extract data I get the error from above.

Edit here's an example of the API data returned:

{
  "coord": {
    "lon": -96.81,
    "lat": 32.78
  },
  "weather": [
    {
      "id": 804,
      "main": "Clouds",
      "description": "overcast clouds",
      "icon": "04d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 295.15,
    "pressure": 1016,
    "humidity": 78,
    "temp_min": 294.15,
    "temp_max": 296.15
    },
  "visibility": 20921,
  "wind": {
    "speed": 4.1,
    "deg": 180
  },
  "clouds": {
    "all": 100
  },
  "dt": 1491835980,
  "sys": {
    "type": 1,
    "id": 2596,
    "message": 0.0099,
    "country": "US",
    "sunrise": 1491825755,
    "sunset": 1491872065
  },
  "id": 4684888,
  "name": "Dallas",
  "cod": 200
}
HellaDev
  • 408
  • 2
  • 8
  • 24
  • Post an example of API response – hindmost Apr 10 '17 at 14:58
  • Where are you actually making the request to the API? – LiverpoolOwen Apr 10 '17 at 14:59
  • Oops, sorry I meant to do that. It's added now. – HellaDev Apr 10 '17 at 15:00
  • Are you sure that's what you're getting? The JSON error doesn't apply to your example. – evolutionxbox Apr 10 '17 at 15:01
  • 3
    In fact isn't `data` just a URL... _not JSON_? Seeing as the AJAX call is never made. – evolutionxbox Apr 10 '17 at 15:02
  • Yeah @evolutionxbox I think your right – LiverpoolOwen Apr 10 '17 at 15:04
  • @evolutionxbox this is where I'm trying to learn. I guess upon your responses a better question is, what do I do to make that URL a JSON object inside my app? I added the rest of my application code to my post for a better picture of everything. This is literally my first API app ever so I might be on the completely wrong path here. – HellaDev Apr 10 '17 at 15:06
  • Then look right here... http://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery – evolutionxbox Apr 10 '17 at 15:08
  • @evolutionxbox I didn't realize I had to use AJAX. Thank you! I'll look into that. If you have any recommended reading/docs on understanding how the whole API system works I'd really appreciate it. As of right now I am sort of arbitrarily searching for ways to work with APIs but nothing I find breaks it all down (in a general sense). – HellaDev Apr 10 '17 at 15:10

1 Answers1

0
let fullPath = api + city + "&APPID=" + apiKey + units; // fullPath is a string representing an URL
let data = fullPath; // data is a string representing an URL
let obj = JSON.parse(data); // You try to parse an URL, not JSON

You try to parse an URL, so it doesn't work. Make a XHR request on this URL to get your JSON data.

Edit:

To request a remote JSON file, use the fetch API (include a polyfill if your browser doesn't implement fetch):

fetch('/data.json')
  .then(function(response) {
    return response.json();
}).then(function(json) {
    console.log('parsed json', json);
}).catch(function(ex) {
    console.log('parsing failed', ex);
})
Jérémie L
  • 770
  • 4
  • 14