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"
} また、同じディレクトリ(フォルダ)にJavaScriptファイル 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ランタイム環境のみ)
ブラウザで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>
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'
} -
JavaScriptファイルを動的にロードする方法は?
以下は、JavaScriptファイルを動的にロードするためのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> &nb
-
JavaScriptを使用してJSON配列からデータを読み取る方法は?
以下は、JavaScriptを使用してJSON配列からデータを読み取るためのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style