DEV Community

Mark
Mark

Posted on

How to Read a JSON File in JavaScript

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

Top comments (1)

Collapse
 
jennijuli3 profile image
Jenni Juli

Best content thank you for posting. Best software Training institute in chennai for all the software related courses.