假设我们有一个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": "http://localhost:3000" }
在同一目录(文件夹)中,我们有一个JavaScript文件index.js。
我们的任务是通过JavaScript文件访问json文件的内容。
如果我们在NodeJS环境中运行JavaScript文件,则可以使用require模块访问json文件。
为此的代码将是-
const configData = require('./config.json'); console.log(typeof configData); console.log(configData);
如果要在浏览器中运行JavaScript时访问json文件,可以使用ES6导入语法来实现。
为此的代码将是-
<!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" xx_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: 'http://localhost:3000' }