Computer >> Máy Tính >  >> Lập trình >> Javascript

Cách đọc tệp JSON bên ngoài bằng JavaScript

Giả sử chúng ta có tệp JSON config.json chứa dữ liệu sau -

{
   "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"
}

Và trong cùng một thư mục (thư mục), chúng tôi có một tệp JavaScript index.js .

Nhiệm vụ của chúng ta là truy cập nội dung của tệp json thông qua tệp JavaScript.

Phương pháp 1:Sử dụng mô-đun yêu cầu (chỉ với môi trường NodeJS)

Chúng tôi có thể sử dụng mô-đun yêu cầu để truy cập tệp json nếu chúng tôi đang chạy tệp JavaScript của mình trong môi trường NodeJS.

Ví dụ

Mã cho điều này sẽ là -

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

Phương pháp 2:Sử dụng mô-đun nhập ES6 (chỉ dành cho Môi trường thời gian chạy web)

Nếu chúng tôi muốn truy cập tệp json trong khi chạy JavaScript trong trình duyệt, chúng tôi có thể sử dụng cú pháp nhập ES6 để thực hiện điều đó.

Ví dụ

Mã cho điều này sẽ là -

TẬP TIN 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>

TẬP TIN JAVASCRIPT:

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

Đầu ra

Và đầu ra sẽ là -

{
   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'
}