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

393
Vistas
Is there a way to import a .json file into js instead of putting it directly in the code?

I have a very long bit of json that looks a bit like this:

{
  "section: [
   [stuff]
  ]
}

and I'm currently doing this to get it into my js code:

var obj = {

  // {All the stuff from above}
}

I want to put it into a json file that can be locally imported to a js script to work like something like this:

var obj = "path/file.json";

and have it work the same way

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

0

You can use AJAX for this with fetch.

const pathToJson = "./path/file.json";
fetch(pathToJson)
  .then(res => res.json())
  .then(json => {
    console.log(json.section);
  });

Note: this only works with a server. If you are using the file:/// protocol, please switch to a regular server, for example if you have Python installed you can run in your directory: python3 -m http.server.

Another (non-ideal) alternative is to create another JavaScript file with your JSON. Inside it put something like:

var obj = {
  "section": {
    ...
  }
}

Then you can link it in your HTML in a script tag before your running script:

<script src="./json-data.js"></script>
<script src="./my-script.js"></script>

And in my-script.js:

console.log(obj.section); // {...}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Using fetch with async will allow you to use it without callbacks.

More details here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

async function loadJSON() {
  var file = await fetch("/path/to/file.json");
  var obj = await file.json();
  // use object like usual here
}
loadJSON();
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