How can I retrieve JSON information from the wunderground API?

I have an async function below that connects to a weather API and I am trying to extract two data points: Temperature in Fahrenheit & Celsius. The API_Key has been removed, but it can be obtained for free on the site if needed.

Although my console.log(response) statement confirms that I am receiving the json object, I am unsure of how to access these specific data points within the heavily nested json structure.

For example, when attempting to access 'full' for the full city name by using response.observation_location.full, it does not yield the desired result...

Any assistance would be greatly appreciated.

async loadWeather() {
        // let zip = this.args.zip || 97239;
        let response = await fetch(`http://api.wunderground.com/api/API_KEY/conditions/q/CA/San_Francisco.json`);
        console.log(response);
        this.weather = await response.json();
        // setTimeout( () => { this.loadWeather(); }, 2000);
    }

Below is a snippet from the response json:

{
    "response": {
        "version": "0.1",
        "termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
        "features": {
            "conditions": 1
        }
    },
    "current_observation": {
        "image": {
            "url": "http://icons.wxug.com/graphics/wu2/logo_130x80.png",
            "title": "Weather Underground",
            "link": "http://www.wunderground.com"
        },
        "display_location": {
            "full": "San Francisco, CA",
            "city": "San Francisco",
            "state": "CA",
            "state_name": "California",
            "country": "US",
            "country_iso3166": "US",
            "zip": "94102",
            "magic": "1",
            "wmo": "99999",
            "latitude": "37.77999878",
            "longitude": "-122.41999817",
            "elevation": "60.0"
        },
        "observation_location": {
            "full": "SOMA, San Francisco, California",
            "city": "SOMA, San Francisco",
            "state": "California",
            "country": "US",
            "country_iso3166": "US",
            "latitude": "37.778488",
            "longitude": "-122.408005",
            "elevation": "23 ft"
        },

I have attempted

console.log(response["current_observation"])
to access a nested data value, however, it returns undefined.

Answer №1

So I managed to figure out the solution by myself, but here's a recap:

The response had to be converted to JSON using response.json()

After that, I was able to access the properties as needed

this.weather = await response.json();
console.log(this.weather["current_observation"]["temp_f"]);
console.log(this.weather["current_observation"]["temp_c"]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to restrict datalist options while preserving the "value" functionality?

After finding a creative solution by @Olli on Limit total entries displayed by datalist, I successfully managed to restrict the number of suggestions presented by a datalist. The issue arises from the fact that this solution only covers searching through ...

Using JSON as a command line argument on Unix systems

When attempting to pass a JSON string as a command line argument to my C++ application in a Unix environment, I encountered an issue. .\SampleApp -j {\"speed\":\"15\",\"rpm\":\"100\",\"loc\":[\"- ...

Synchronize JSON data with the Document Object Model (DOM

My current project is built using React, where I am rendering the page dynamically based on JSON data. The page consists of various component types, ranging from images to text content. Each component includes a delete option, allowing users to change im ...

What could be causing webpack to struggle in locating the loader?

Check out my package.json: { "name": "redux-todo", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "webpack-dev-server" }, "devDependencies": { "babel": "^6.5.2", "babel-loader": "^6.2.5", "bab ...

D3 group of legendary elements

Is there a way to group both the circle and text elements for each legend item together? I'm currently facing a challenge with the enter/exit methods. While I can create the groups (g), I'm unable to append the text and circle elements. li.sel ...

HTML is loaded repeatedly using the ajax load() function, without involving JSON

My idea involves the seamless loading of HTML files from one to another. The visual representation below can provide a better understanding. To illustrate, there are several HTML files - no1.html, no2.html, no3.html, no4.html, etc. - all sharing a common J ...

Unit testing in Angular: Testing HTTP functionality with live APIs

I am currently working on writing unit tests in Angular CLI using Karma. I'm trying to test HTTP calls with a real API instead of using mocks because the API models tend to change frequently. I want to ensure that my endpoint responses are accurate. I ...

Trouble encountered while using useRef in TypeScript

I'm encountering an issue with the code below; App.tsx export default function App() { const [canvasRef, canvasWidth, canvasHeight] = useCanvas(); return ( <div> <canvas ref={canvasRef} /> </div> ) ...

How can I import tamplateData into my JavaScript files in Docpad?

Looking for a DocPad plugin that can preprocess JS files and utilize templateData variables and helpers to access configuration values. While experimenting with Hogan, I managed to retrieve the variables but encountered difficulty in invoking the helpers. ...

Guide to resetting a CSS animation with pure JavaScript

My flexbox contains 4 images, each triggering an animation on hover. However, the animation stops if I hover over the same image again. I have tried various JavaScript solutions found online to restart the animation, but none seem to be working for me. S ...

What is the best way to sort my API responses to display only users who are either currently online or offline?

Hi everyone, I've made great progress on my project so far without any assistance (pretty proud of myself), but now I could use some help. I'm working on creating a tabbed menu that filters the results of my API calls to display: All users, Onlin ...

Utilizing Jquery for comparing and retrieving string arrays

Hey there! I'm currently working on a jQuery application and I'm facing an issue with comparing two arrays. Here is an example: FirstArray=["Mike","Jack"]; SecondArray=["Mike","Jack","Andy","Cruz"]; I want to find out which strings are common i ...

Enhancing JSON Formatting with Angular 4 and Typescript

In the process of developing my Angular 4 application, I am interfacing with a REST API through JSON requests. As I work on creating JSON objects to send via POST requests, I find myself putting in quite a bit of manual effort to construct them... I KNOW ...

To begin, formulating a blank state entity containing a collection of key-value pairs with JSON objects as the values. Subsequently, modifying the contents of

I am working on setting up a reactJS state with an empty array to start. When I receive a message in the form of a JSON object, I want to add a key-value pair to the array, using the received message as the value and a specified key. For example: We have ...

triggering e.stopImmediatePropagation() within an onclick event handler

Is there a way to retrieve the event object from an onclick attribute? I attempted the following: <a href="something.html" onclick="function(e){e.stopImmediatePropagation();}">Click me</a> In addition, I tried this: <a href="something.ht ...

What is the best way to utilize the existing MUI state in order to calculate and show column totals?

I am currently in the process of developing an MUI web application to keep track of some personal data. Within this application, I have incorporated the MUI datagrid pro component to efficiently display the data with its robust filtering capabilities. In ...

Is there a method to verify if a GeoJSON feature is in the shape of a rectangle and locate its corner coordinates?

I am looking for a way to identify all the corner coordinates of GeoJSON features that are in rectangular or square shape. Some of the features have more than five coordinates but still represent a rectangle or square shape. Is there an algorithm or third- ...

jQuery grid view for checking the status as even or odd

I am facing an issue with a gridview where users input integer numbers in a text box, and a jQuery function should display whether the number is even or odd in another text box in the same row. Below is an example with some columns omitted for simplicity: ...

Preventing special characters in an input field using Angular

I am trying to ensure that an input field is not left blank and does not include any special characters. My current validation method looks like this: if (value === '' || !value.trim()) { this.invalidNameFeedback = 'This field cannot ...

When an iteration occurs within a for loop and a value changes, remember to incorporate a line break or equivalent element using jQuery

I am currently working on implementing a hierarchy system for users stored in a database table. At the moment, only top-level users with a hierarchy of 1 are displayed. When clicked, I use AJAX to retrieve and display all related users below them. These ...