Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

366
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda