gpt4 book ai didi

javascript - 如何从 API 显示特定 JSON 数据

转载 作者:太空宇宙 更新时间:2023-11-04 01:40:26 24 4
gpt4 key购买 nike

I'm using got for requests.

代码:

const response = await got(`https://airapi.airly.eu/v2/measurements/installation?installationId=204`, {
headers: {
apikey: `API_KEY`
},
json: true
});

console.log(response.body.current.values);

输出:

[ { name: 'PM1', value: 20.72 },
{ name: 'PM25', value: 32.43 },
{ name: 'PM10', value: 61.22 },
{ name: 'PRESSURE', value: 1028.46 },
{ name: 'HUMIDITY', value: 91.59 },
{ name: 'TEMPERATURE', value: 10.87 } ]

现在,我想以这种格式向用户显示它:

PM1: 20.72 µg/m3 
PM25: 32.43 µg/m3
PM10: 61.22 µg/m3

我的问题是:最好的方法是什么?以后我也想用https://www.chunqiuyiyu.com/ervy/这样的库,所以最好以某种方式分离这些数据。我希望我已经说清楚了:)

最佳答案

看起来 Envy 使用特定的数据结构,因此您首先需要转换现有数据:

const data = arr.map(el => ({ ...el, key: el.name }));

然后你就可以map覆盖元素,然后用换行符将它们连接起来,将它们打印到控制台。

演示:

const arr = [{"name":"PM1","value":20.72},{"name":"PM25","value":32.43},{"name":"PM10","value":61.22},{"name":"PRESSURE","value":1028.46},{"name":"HUMIDITY","value":91.59},{"name":"TEMPERATURE","value":10.87}];

// create an envy structure from the original data using `map`
const data = arr.map(el => ({ ...el, key: el.name }));

// `map` over that data and return an array of strings
// separated by line breaks
const str = data.map(el => `${el.key}: ${el.value} µg/m3`).join('\n');

console.log(str);

关于javascript - 如何从 API 显示特定 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53134987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com