如何在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": "http://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" xx_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: 'http://localhost:3000'
}