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

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

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 Relatório

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 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