สมมติว่าเรามีไฟล์ JSON ชื่อ config.json ที่มีข้อมูล:
{
"secret": "sfsaad7898fdsfsdf^*($%^*$",
"connectionString": "mongodb+srv://username:password@cluster0.laaif.mongodb.net/events?retryWrites=true&w=majority",
"localConnectionString": "mongodb+srv://username:password@cluster0.laaif.mongodb.net/eventsLocal?retryWrites=true&w=majority",
"frontendClient": "https://helloworld.com",
"localFrontendClient": "https://localhost:3000"
}
และในโฟลเดอร์เดียวกัน มีไฟล์ JavaScript ชื่อ index.js ภารกิจคือเข้าถึงเนื้อหาไฟล์ JSON ผ่านไฟล์ JavaScript
วิธี 1: ใช้โมดูล require (เฉพาะ NodeJS)
ใช้ require เพื่อเข้าถึงไฟล์ JSON ถ้ารัน JavaScript ในสภาพแวดล้อม NodeJS
const configData = require('./config.json');
console.log(typeof configData);
console.log(configData);
วิธี 2: ใช้โมดูล import ES6 (เฉพาะ Web Runtime)
ถ้าต้องการเข้าถึงไฟล์ JSON ขณะรัน JavaScript ในเบราว์เซอร์ ใช้ไวยากรณ์ import ของ ES6
ไฟล์ HTML:
READ JSON FILE
ไฟล์ 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=true&w=majority',
localConnectionString: 'mongodb+srv://username:password@cluster0.laaif.mongodb.net/eventsLocal?retryWrites=true&w=majority',
frontendClient: 'https://helloworld.com',
localFrontendClient: 'https://localhost:3000'
}