[英]Formatting JSON response API call in Typescript
我是 Typescript 的新手,想使用 Firebase 函数构建一个简单的天气应用程序。 首先,我想拨打 API 来简单地检索城市的当前温度。
这是来自 API 调用的 JSON 响应:
{
"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"
},
我想在拨打 API 电话时简单地从当前天气中检索温度,这是我当前的代码:
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¤t_weather=true");
const data = await dataResponse.json();
console.log(data);
response.send(data);
});
我如何才能从 JSON 响应中只获得一个值(温度)?
欢迎来到堆栈溢出!
因此,您似乎想要访问 JSON Object 中的一个值,该值是从 API 调用返回的。 在 JavaScript 中,你可以这样做:
myObj.<nested_item1>
所以在你的情况下,你想要
// should be 12.3 based off your response
const temperature = data.current_weather.temperature
希望这可以帮助!
编辑:TypeScript
在 TypeScript 中,如果你没有明确指定你的数据结构,TS 会尝试自动推断数据。 在你的例子中,你正在进行一个 fetch 调用,这意味着 TS 没有关于 output 是什么的上下文。
想象一下,从 TS 的角度来看,你点击的 url 可能包含一个 API 电话、一个网站,或者任何东西。
要解决此问题,您有两种选择:
// @ts-ignore
const temperature = data.current_weather.temperature
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
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.