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
}