You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js API响应中如何动态生成指定格式的JSON结构?

问题:修改天气API响应格式为对象而非数组

输入数据

我提供的输入如下:

{
    "cities" : [
        "kolkata",
        "mumbai",
        "chennai"
    ]
}

当前响应

当前收到的响应为:

{
    "weather": [
        {
            "chennai": "30C"
        },
        {
            "mumbai": "27C"
        },
        {
            "kolkata": "26C"
        }
    ]
}

期望响应

期望得到的响应格式:

{
    "weather" : {
        "kolkata" : "26C",
        "mumbai": "27C",
        "chennai": "30C"
    }
}

现有代码

我的代码如下:

const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const request = require('request');
const app = express();

const apiKey = 'c6068c4018def9330b01366aed03b08e';

app.use(express.static('public'));
app.use(bodyParser.json());

router.post('/getWeather', function (req, res) {
    let cities = req.body.cities;
    let weatherJson = [];

    for(let i=0; i<cities.length; i++)
    {
        let city = cities[i];
        let url = `http://api.weatherstack.com/current?access_key=${apiKey}&query=${city}`;
        request(url, function (response, body) {
            if (response) {
                return res.json({ error: response });
            }
            let weather = JSON.parse(body.body);
            if (weather.current == undefined) {
                return res.json({ error: "somethin went wrong!" });
            }
            let weatherText = `${weather.current.temperature}C`;
            weatherJson.push({ [city] : weatherText });
            if(weatherJson.length == cities.length) {
                console.log("here");
                res.json({"weather": weatherJson});
            }
        });
    }
});

app.use('/', router);

app.listen(3000, function () {
    console.log('Example app listening on port 3000!')
});

问题描述

我尝试过用哈希表、先以数组格式存储再序列化等方法,但都无效。希望通过最小化代码改动实现预期的响应格式,恳请帮助。


解决方案

只需要3处小改动即可实现需求:

  1. 将weatherJson从数组改为空对象
  2. 替换数组push操作为对象属性赋值
  3. 修正request回调的参数顺序(原代码错误地将response作为错误判断条件)

修改后的核心代码片段:

router.post('/getWeather', function (req, res) {
    let cities = req.body.cities;
    let weatherJson = {}; // 改为对象

    for(let i=0; i<cities.length; i++)
    {
        let city = cities[i];
        let url = `http://api.weatherstack.com/current?access_key=${apiKey}&query=${city}`;
        // 修正request回调参数顺序:error在前,response在后
        request(url, function (error, response, body) {
            if (error) {
                return res.json({ error: error });
            }
            let weather = JSON.parse(body);
            if (weather.current == undefined) {
                return res.json({ error: "somethin went wrong!" });
            }
            let weatherText = `${weather.current.temperature}C`;
            weatherJson[city] = weatherText; // 直接给对象赋值
            // 用Object.keys判断已完成请求的城市数量
            if(Object.keys(weatherJson).length == cities.length) {
                console.log("here");
                res.json({"weather": weatherJson});
            }
        });
    }
});

内容的提问来源于stack exchange,提问作者Aratrik Chakraborti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 12:39:24