How to read an external JSON file in JavaScript


Suppose we have a JSON file config.json that contains the following data −

{
   "secret": "sfsaad7898fdsfsdf^*($%^*$",
   "connectionString":
   "mongodb+srv://username:password@cluster0.laaif.mongodb.net/events?retryWrites=tr
   ue&w=majority",
   "localConnectionString":
   "mongodb+srv://username:password@cluster0.laaif.mongodb.net/eventsLocal?retryWrit
   es=true&w=majority",
   "frontendClient": "https://helloworld.com",
   "localFrontendClient": "http://localhost:3000"
}

And in the same directory (folder), we have a JavaScript file index.js.

Our task is to access the content of the json file through the JavaScript file.

Method 1: Using require module (NodeJS environment only)

We can use the require module to access the json file if we are running our JavaScript file in NodeJS environment.

Example

The code for this will be −

const configData = require('./config.json');
console.log(typeof configData);
console.log(configData);

Method 2: Using ES6 import module (Web Runtime Environment only)

If we want to access the json file while running JavaScript in browser, we can use the ES6 import syntax to do that.

Example

The code for this will be −

HTML FILE:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>READ JSON FILE</title>
</head>
<body>
<p id='main'></p>
<script type="module" src="./index.js"></script>
</body>
</html>

JAVASCRIPT FILE:

import configData from './config.json';
document.getElementById('main').innerHTML = JSON.stringify(configData);

Output

And the output will be −

{
   secret: 'sfsaad7898fdsfsdf^*($%^*$',
   connectionString:
   'mongodb+srv://username:password@cluster0.laaif.mongodb.net/events?retryWrites=tr
   ue&w=majority',
   localConnectionString:
   'mongodb+srv://username:password@cluster0.laaif.mongodb.net/eventsLocal?retryWrit
   es=true&w=majority',
   frontendClient: 'https://helloworld.com',
   localFrontendClient: 'http://localhost:3000'
}

Updated on: 22-Feb-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements