Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

JavaScript에서 외부 JSON 파일을 읽는 방법

<시간/>

다음 데이터를 포함하는 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"
}

그리고 같은 디렉토리(폴더)에 자바스크립트 파일 index.js가 있습니다. .

우리의 임무는 JavaScript 파일을 통해 json 파일의 내용에 액세스하는 것입니다.

방법 1:require 모듈 사용(NodeJS 환경만 해당)

NodeJS 환경에서 JavaScript 파일을 실행하는 경우 require 모듈을 사용하여 json 파일에 액세스할 수 있습니다.

예시

이에 대한 코드는 -

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

방법 2:ES6 가져오기 모듈 사용(Web Runtime Environment만 해당)

브라우저에서 JavaScript를 실행하는 동안 json 파일에 액세스하려면 ES6 가져오기 구문을 사용하면 됩니다.

예시

이에 대한 코드는 -

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>

자바스크립트 파일:

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