Lesson 253 – Complete 2020 Web Development Bootcamp

Lesson 253 – How to Parse JSON

This lesson deals with how to get the API data from the response.on() method and then how to parse the JSON data that we get back into an actual javascript object. We also how to get and use specific pieces of the object.

In the code below – I’ve made comments on what is being done with regard to getting the JSON data, parsing it and using it.

const express = require("express");

//creates constant variable which requires npm https
const https = require("https");

const app = express();

//express get function to get data from openweathermap API
app.get("/", function(req, res) {

   //creates constant variable url which is the openweathermap API   
   const url = "https://api.openweathermap.org/data/2.5/weather?q=London&appid=3dcdddca4ff444218db3b27a7394e1a7&units=imperial";

   //uses npm https get method to obtain data from openweathermap API
	https.get(url, function(response) {

   //uses response.on to parse with JSON.parse method the data received from openweathermap API

		response.on("data", function(data) {

			const weatherData = JSON.parse(data);

			const temp = weatherData.main.temp;

 //creates constant variable WeatherDescription from data parsed from the JSON data received from the openweathermap API
			const weatherDescription = weatherData.weather[0].description;

  
			console.log(weatherDescription);

		});

	});

	res.send("Server is up and running.");

});