Typescript implementation for structuring JSON response data from API calls

As a beginner in Typescript, I am eager to create a straightforward weather application using Firebase functions. One of the initial steps involves making an API call to fetch the current temperature of a particular city.

Upon making the API call, the JSON response provided includes various details such as latitude, longitude, timezone, and most importantly, the current weather data containing temperature information.

{
"latitude": 40.710335,
"longitude": -73.99307,
"generationtime_ms": 0.3579854965209961,
"utc_offset_seconds": 0,
"timezone": "GMT",
"timezone_abbreviation": "GMT",
"elevation": 27.0,
"current_weather": {
    "temperature": 12.3,
    "windspeed": 14.0,
    "winddirection": 181.0,
    "weathercode": 3,
    "time": "2023-01-13T09:00"
},
"hourly_units": {
    "time": "iso8601",
    "temperature_2m": "°C"
},

In order to extract only the temperature value from the current weather section of the JSON response, I have been working on the following code snippet:

export const getWeather = functions.https.onRequest(async (request, response) => {
  const dataResponse = await fetch("https://api.open-meteo.com/v1/forecast?latitude=40.71&longitude=-74.01&hourly=temperature_2m&current_weather=true");
  const data = await dataResponse.json();

  console.log(data.current_weather.temperature); // This line retrieves the temperature value
  response.send(data.current_weather.temperature); // Sending only the temperature value in the response
});

I am exploring ways to efficiently extract and utilize specific values like temperature from complex JSON responses generated by API calls.

Answer №1

Welcome to the wonderful world of Stack Overflow!

It seems like you're interested in extracting a value from the JSON Object returned by an API Call. In JavaScript, you can achieve this by:

myObj.<nested_item1>

In your specific scenario, you'd want something like this:

// The expected result should be 12.3 based on your input
const temperature = data.current_weather.temperature 

I hope this clarifies things for you!

Edit: Let's talk TypeScript

When working with TypeScript and dynamic data structures like the one retrieved from a fetch call, it's important to provide TS with enough context to understand the data format.

From TypeScript's perspective, the endpoint you're hitting could return various types of content.

To address this issue, there are two solutions:

  1. Temporarily disable type checking for that line (not recommended)
// @ts-ignore
const temperature = data.current_weather.temperature 
  1. Define the structure of the fetch response using interfaces or types

type WeatherData = {
  latitude: number
  longitude: number
  generationtime_ms: number
  utc_offset_seconds: number
  timezone: string
  timezone_abbreviation: string
  elevation: number
  current_weather: {
    temperature: number
    windspeed: number
    winddirection: number
    weathercode: number
    time: string
  }
  hourly_units: {
    time: string
    temperature_2m: string
  }
}

...
const data = await dataResponse.json() as WeatherData
...

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

Error: The property 'open' is not defined in the mdMenu object

Encountered a bug while working with angular-material design... When using md-menu, if a sub menu item is opened (as shown in the image) and then hovering over a non-subMenu item (menu item), it throws an error "Cannot read property 'open' of nul ...

Troubleshooting issues with Docker and Angular 2: unable to retrieve data

We are in the process of setting up an Angular 2 application with Docker by following a tutorial available at: https://scotch.io/tutorials/create-a-mean-app-with-angular-2-and-docker-compose Although the application deploys successfully, we encounter an i ...

Fully responsive header designed for optimal experience at any screen height

I am facing issues with the header and cannot seem to find a solution. My goal is to make the header span 100% of the window screen height. I need a responsive header that adjusts to 100% height, and when resizing for a smaller viewport, nothing should sho ...

Utilizing THREE.JS Raycaster with JavaScript "entities" rather than just meshes

I am facing a challenge with the Raycaster model. I grasp the concept of how it intersects meshes that can be transformed, but my issue lies in identifying when the specific instance of an object is clicked. Consider a scenario where there is a button. Th ...

What is the best way to retrieve and display data from a JSON object that has been encoded using json_encode on one page.php, in another page.php?

I have a specific requirement that involves calling JSON data from one PHP page and displaying it on another PHP page. Can someone guide me on how to achieve this? Below is the JSON code that I need to retrieve: <?php include("Connect.php"); $Db = m ...

Condition in Bash script for verifying JSON response

This particular script is designed to notify me whenever there is an error response. Problem: Even when the execution is successful, I am still receiving an email. Bash script: #!/bin/bash DATA=$(wget --timeout 5 -O - -q -t 1 http://this.url/?parm=1&bs ...

What is the best way to implement a link instead of a string within a custom JavaScript function?

I am looking for a way to replace parameters in a string with the values provided using a helper function - type FormatStringParameter = string | number; /** * Helper function to substitute parameters in a string with the specified values * * @param in ...

Sending information to a PHP script using Ajax

I am working on a project that involves input fields sending data to a PHP page for processing, and then displaying the results without reloading the page. However, I have encountered an issue where no data seems to be passed through. Below is my current s ...

Get the final element with a for loop in Angular 2

I am currently utilizing angular 2 in conjunction with mongoDb. The service I am employing is responsible for calling the API. Here is a snippet of my code: this.at represents a token, similar to fdfdsfdffsdf... This token serves as an authorization key ...

In JavaScript, use the following code to replace "(" with "(":

Is there a way to dynamically transform the string "Test(5)" into "Test\(5\)" using JQuery or Javascript? I attempted this approach, but it did not work as expected var str = "Test(5)"; str = str.replace("(","\("); str = str.replace(")"," ...

Divide a JSON API object into segments within an express application

One way I'd like to organize my API's output is by splitting it into multiple pages. My idea is to access them using URLs like this: http://127.0.0.1:3000/api/articles/0/<API-TOKEN> This specific URL would display the first page containing ...

What is the best way to individually update fields using Prisma?

I am facing a challenge with updating fields individually for an object named Post. This object has three fields: title, content, and summary. Situation To save a post in the database, I can fill in just the title field initially and leave the other fiel ...

Combine functions from two objects that share the same properties into an array for each property

I need help combining the methods from two objects into one, resulting in an array of methods for each property in the parent object: obj1 = {"prop1":"method1","prop2":"method2"} obj2 = {"prop1":"method3","prop2":"method4"} Expected result: obj1 = {"pro ...

What is the best way to transform JSON into a structured nested array?

Suppose there is a JSON dataset with latitude, longitude, and location details. The objective is to extract only the latitude and longitude values from this data and return them as a JSON string in Python. How can this be achieved in Python programming la ...

I am looking to implement user authentication using firebase, however, the sign-in page is currently allowing invalid inputs

<script> function save_user() { const uid = document.getElementById('user_id'); const userpwd = document.getElementById('user_pwd'); const btnregister=document.getElementById('btn-acti ...

HTML/Javascript/CSS Templates: Keeping Tabs on Progress

I'm looking for templates that use notepad as an editor for html/javascript/css. I want to find a template that displays text or pictures upon clicking, like the example below: https://i.sstatic.net/qsFYs.png Sorry if this is a silly question, it&ap ...

Gracefully Switching Between Various Functions

Suppose I have a collection of functions that perform various tasks: function doSomething() { console.log('doing something'); } function accomplishTasks() { console.log('accomplishing tasks'); } function executeAction() { console. ...

Merge data from api into visual charts using Google Chart Library

I received an API response with the following data structure: { "status": 200, "message": "OK", "data": [ { "_id": { "report_type": "robbery" }, "report_type": "robbery", "Counts": 11 }, { "_id": { "repo ...

The functions firebase.auth().currentUser and onAuthStateChanged consistently return null even when the user is logged in

Despite the fact that my front end Swift application indicates that the user is signed in, I am encountering an issue where firebase.auth().currentUser and the onAuthStateChanged listener in my node.js code return null. The backend service is called from t ...

Can the top header stay fixed to the top of the screen even when scrolling down?

Code snippet: http://jsfiddle.net/R3G2K/1/ In my project, there are multiple divs with content and each div has a header. My goal is to make the last header that goes out of viewport "sticky" or fixed at the top. I have explored various solutions for thi ...