Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

วิธีอ่านไฟล์ JSON ภายนอกใน JavaScript


สมมติว่าเรามีไฟล์ JSON config.json ที่มีข้อมูลดังต่อไปนี้ -

<ก่อนหน้า>{ "ความลับ":"sfsaad7898fdsfsdf^*($%^*$", "connectionString":"mongodb+srv://username:password@cluster0.laaif.mongodb.net/events?retryWrites=tr ue&w=ส่วนใหญ่", "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 .

งานของเราคือการเข้าถึงเนื้อหาของไฟล์ json ผ่านไฟล์ JavaScript

วิธีที่ 1:การใช้โมดูล require (สภาพแวดล้อม NodeJS เท่านั้น)

เราสามารถใช้โมดูล require เพื่อเข้าถึงไฟล์ json หากเรากำลังเรียกใช้ไฟล์ JavaScript ในสภาพแวดล้อม NodeJS

ตัวอย่าง

รหัสสำหรับสิ่งนี้จะเป็น −

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

วิธีที่ 2:การใช้โมดูลการนำเข้า ES6 (สภาพแวดล้อมรันไทม์ของเว็บเท่านั้น)

หากเราต้องการเข้าถึงไฟล์ json ขณะเรียกใช้ JavaScript ในเบราว์เซอร์ เราสามารถใช้ไวยากรณ์การนำเข้า ES6 เพื่อดำเนินการดังกล่าวได้

ตัวอย่าง

รหัสสำหรับสิ่งนี้จะเป็น −

HTML FILE:

อ่านไฟล์ JSON

ไฟล์จาวาสคริปต์:

นำเข้า configData จาก './config.json';document.getElementById('main').innerHTML =JSON.stringify(configData);

ผลลัพธ์

และผลลัพธ์จะเป็น −

{ ความลับ:'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'}