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

Time:03-02

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

CodePudding user response:

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); // {...}

CodePudding user response:

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();

CodePudding user response:

You can require that JSON file in your code like this

const jsonData = require("./json-file-path");

If you are using ES6:

import jsonData from ('./json-file-path');

and you also need to add this "resolveJsonModule": true option to your tsconfig.json compilerOptions object.

  • Related