मान लीजिए हमारे पास एक JSON फ़ाइल config.json है जिसमें निम्नलिखित डेटा है:
{
"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": "https://localhost:3000"
}
और उसी डायरेक्टरी (फ़ोल्डर) में, हमारे पास एक JavaScript फ़ाइल index.js है।
हमारा कार्य JavaScript फ़ाइल के माध्यम से JSON फ़ाइल की सामग्री तक पहुंचना है।
विधि 1: require मॉड्यूल का उपयोग करना (केवल NodeJS वातावरण)
यदि हम अपनी JavaScript फ़ाइल को NodeJS वातावरण में चला रहे हैं तो हम JSON फ़ाइल तक पहुंचने के लिए require मॉड्यूल का उपयोग कर सकते हैं।
उदाहरण
const configData = require('./config.json');
console.log(typeof configData);
console.log(configData);
विधि 2: ES6 import मॉड्यूल का उपयोग करना (केवल वेब रनटाइम वातावरण)
यदि हम ब्राउज़र में JavaScript चलाते समय JSON फ़ाइल तक पहुंचना चाहते हैं, तो हम ऐसा करने के लिए ES6 import सिंटैक्स का उपयोग कर सकते हैं।
उदाहरण
HTML फ़ाइल:
<!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 फ़ाइल:
import configData from './config.json';
document.getElementById('main').innerHTML = JSON.stringify(configData);
आउटपुट
और आउटपुट होगा:
{
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: 'https://localhost:3000'
}