Home > front end >  How to I dynamically insert key and value in JSON in the response of NodeJs API
How to I dynamically insert key and value in JSON in the response of NodeJs API

Time:08-15

This is the Input I am providing

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

and this is the response I am receiving.

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

I want a response somewhat like

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

My code is as follows.

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!')
});

I have tried adding as hashmap, adding in array format then using stringify at the response point, but nothing seems to work. I just want to convert the format of the response to the desirable one with as minimalistic change in the code as possible. Please help.

CodePudding user response:

You have a few issues, first off you're storing weatherJson (response) as an array when you say you want it to be a map.

here's how I would implement this:

router.post("/getWeather", async 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}`;
    try {
      const response = await fetch(url);
      let weather = JSON.parse(response.body);
      if (weather.current == undefined) {
        return res.json({ error: "somethin went wrong!" });
      }
      let weatherText = `${weather.current.temperature}C`;
      weatherJson[city] = weatherText;
    } catch (err) {
      return res.json({ error: err });
    }
  }

  res.json({ weather: weatherJson });
});

You should use node-fetch instead of request which is obsolete. It does the same thing but much cleaner with promises instead of callbacks.

CodePudding user response:

try creating an object instead of an array.

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[city]=weatherText;
            if(Object.keys(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!')
});
  • Related