How to Read a JSON File in JavaScript

Mark - Jun 11 - - Dev Community

When you need to read a json file in your project, it is easy to get the idea using fetch or axios.

For example, we have data.json.

{
    "name": "Hello World",
    "age": 18
}
Enter fullscreen mode Exit fullscreen mode

Use fetch to read.

fetch('https://server.com/data.json')
    .then((response) => response.json())
    .then((json) => console.log(json));
Enter fullscreen mode Exit fullscreen mode

It works when your project is running in web browser environment, but when your project is running in hybrid environment, it is file protocol instead of http protocol. You will get cors error.

Image description

You can use script tag to fix this problem.

Change data.json to data.js

window.config = {
    "name": "Hello World",
    "age": 18
}
Enter fullscreen mode Exit fullscreen mode

Add script tag in your html file template.

<!--      <script src="./data.js"> </script>-->
      <script>
          document.write('<script src="./data.js?t=' + new Date().getTime() + '"><\/script>')
      </script>
Enter fullscreen mode Exit fullscreen mode

Now you can read data from window object in your javascript code.

const data = window.config
console.log(data)
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player