Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

127
Vistas
Returning an array as a json response

So Im using a football live matches api

Im taking what i need from the json response and storing it in an array

I want to return the array as a json response when i visit a certain route

Here's the code

var request = require('request');

exports.data = function getData(){


const options = {
  method: 'GET',
  url: 'https://elenasport-io1.p.rapidapi.com/v2/inplay',
  qs: {page: '1'},
  headers: {
    'x-rapidapi-host': 'elenasport-io1.p.rapidapi.com',
    'x-rapidapi-key': 'mykey',
    useQueryString: true
  }
};

request(options, function (error, response, body) {

    var liveMatches = [];
        data = JSON.parse(body);
        var matchesList = data['data'];

    for(let i = 0; i < matchesList.length; i++){
            
             liveMatches.push(
             {
                homeName : matchesList[i]['homeName'],
                awayName : matchesList[i]['awayName'],
                elapsed : matchesList[i]['elapsed'],
                team_home_goals : matchesList[i]['team_home_90min_goals'],
                team_away_goals : matchesList[i]['team_away_90min_goals'],
                createdAt : Date.now()
             }
                );
        }

        for (let j= 0; j<liveMatches.length;j++){
            console.log(liveMatches[j]);
            console.log("--------------------------------------------");
        }

});

}

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I guess that your actual question is how to return the data from inside the getData() function. If that's the case, then you just need to use an awaitable Promise:

var request = require('request');

function getData() {
  const options = {
    method: 'GET',
    url: 'https://elenasport-io1.p.rapidapi.com/v2/inplay',
    qs: { page: '1' },
    headers: {
      'x-rapidapi-host': 'elenasport-io1.p.rapidapi.com',
      'x-rapidapi-key': 'mykey',
      useQueryString: true,
    },
  };

  return Promise((resolve) => {
    request(options, function (error, response, body) {
      data = JSON.parse(body);
      const matchesList = data['data'];

      const liveMatches = [];
      for (let i = 0; i < matchesList.length; i++) {
        liveMatches.push({
          homeName: matchesList[i]['homeName'],
          awayName: matchesList[i]['awayName'],
          elapsed: matchesList[i]['elapsed'],
          team_home_goals: matchesList[i]['team_home_90min_goals'],
          team_away_goals: matchesList[i]['team_away_90min_goals'],
          createdAt: Date.now(),
        });
      }

      resolve(liveMatches); // <--- this is the important part
    });
  });
}

exports.data = getData();

And then you'll use it in similarly to this:

const serverData = await getData();

console.log(serverData); // OK
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda