Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

391
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!