How To Use A Local Json File In Your Javascript Projects.

How To Use A Local Json File In Your Javascript Projects.

Often times, If given the option of using a local JSON file or hardcode my data, I do opt to hardcoding. Honestly the only reason I avoided it was because I was afraid to, never used it before. Until there was a task I had no option than to use the JSON file provided locally.

Found out few ways you can make use of the data in a JSON file for your frontend projects.

1. Using the Fetch API

With your JSON file (e.g data.json) at the root of the directory, you can get the data from your JSON file using the browser fetch() API.

//main.js

fetch('./data.json')
    .then(response => {
        // handle the response
        console.log(response);
    })
    .catch(error => {
        // handle the error
        console.log(error);
    });

The cons of this approach is that by default, browsers restrict access to local files for security reasons. To work around this, ensure that you're working on a HTTP server for local development. You can make use of the likes of live server or localhost.

2. Converting JSON file to javascript

If you don't want to use the fetch() API, you can also convert your local JSON file into javascript. Fortunately, this is pretty easy since JSON syntax is so similar to JavaScript.

//data.json

[{
    "username": "angela",
    "firstName": "Angela",
    "lastName": "Yu"
    },
    {
     "username": "jack",
     "firstName": "Jack",
     "lastName": "Bauer"
    }
]

To convert this JSON file to a javascript code..

  • Make the whole object notation an array and give the array a name.
  • Change the extension of the JSON file to javascript file. That is .json file to .js. The previous data.json file will now be data.js.
//data.js

const data = [{
    "username": "angela",
    "firstName": "Angela",
    "lastName": "Yu"
    },
    {
     "username": "jack",
     "firstName": "Jack",
     "lastName": "Bauer"
    }
]

If you would like to keep your data file separate; as it is now, you would have to use the ES6 export keyword to make your data array available in your main.js.

//data.js

const data = [{
    ...
}]

export default data;

And import the data.js file into main.js

//main.js

import 'data' from './data.js';
console.log(data)

That will be all the javascript configuration to get you started, now you have to also configure HTML. Your script tag should have the type="module" attribute which indicates that it to be considered as a Javascript module.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="wrapper"></div>

    <script src="./data.js" type="module"></script>
    <script src="./main.js" type="module"></script>
</body>
</html>