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

365
Vistas
How to get JSON Array from external json file without using jQuery?

I am working on creating the classical car API. Now I'm trying to pull a JSON Array from an external file. I made a step toward a resolution, however my "solution" will return the full object, instead of the array json. Screenshot from Postman This is from the vehicles.js file, found under api/routes/

import express from 'express';    
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const router = express.Router();
router.get('/', (req, res, next) => {
    res.status(200).sendFile(path.join(__dirname, '../resources', 'vehicles.json'));
});
export default router;

The app.js looks like this:

import express from 'express';      
const app = express();     

import vehiclesRoute from './api/routes/vehicles.js';


app.use('/vehicles', vehiclesRoute);                                  

export default app; 

Something else I tried was in the lines of:

import parsedJSON from './resources/vehicles.json';
var vehiclesJSON = parsedJSON.vehicles;

router.get('/', (req, res, next) => {
    let vehiclesJSONpath = path.join(__dirname, '../resources', 'vehicles.json');
    res.status(200).fetch(vehiclesJSONpath)
  .then(res => res.json())
  .then(data => console.log(data));
});
  1. Is there a way I can do the parsing and include it in the response body of the callback?
  2. Is there maybe a route I need to configure anew, so that the array can be simply extracted? Thanks!
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Will close this. The solution was simple.

'use strict';
let rawdata = fs.readFileSync('api/resources/vehicles.json');
let vehicles = JSON.parse(rawdata);

Then, in order to be able to get it as a response:

router.get('/', (req, res, next) => {
    res.status(200).json(vehicles);
});

Saved by: https://stackabuse.com/reading-and-writing-json-files-with-node-js/

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