How to Import a JSON File in JavaScript
Importing JSON files is a common requirement for loading configuration, data, or settings into a JavaScript application. The method you use depends on your environment: modern browsers and Node.js support direct JSON module imports, while older environments rely on fetching the file or using Node.js's built-in require function.
This guide will cover the modern ES Module approach using import assertions, which is the current standard, as well as the classic fetch() method for browsers and the require() function for Node.js.
The Modern Method: ES Module Import Assertions
The latest and most direct way to import a JSON file is to treat it as a module. This requires using an import assertion (with { type: 'json' }), which tells the JavaScript engine to parse the file as JSON, not as executable code.
Syntax:
import data from './example.json' with { type: 'json' };
console.log(data);
This syntax recently changed from assert to with. While assert is still supported for backward compatibility in many environments, with is the new standard.
This method requires your environment to be configured to use ES Modules.
In the Browser
To use this in a browser, you must add type="module" to your <script> tag.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>JSON Import</title>
</head>
<body>
<!-- This enables ES Module features, including JSON imports -->
<script type="module" src="index.js"></script>
</body>
</html>
JavaScript (index.js):
// index.js
import config from './config.json' with { type: 'json' };
console.log(config.version); // Output: '1.0.0'
console.log(config.api.url); // Output: 'https://api.example.com'
This is the cleanest and most declarative way to load JSON in modern browsers.
In Node.js
To use ES Module imports in Node.js:
- Ensure you are using a modern version of Node.js (v16.14+ recommended).
- Configure your project to use ES Modules by either:
- Saving your files with an
.mjsextension. - Adding
"type": "module"to yourpackage.jsonfile.
- Saving your files with an
package.json:
{
"name": "my-node-app",
"type": "module",
"version": "1.0.0"
}
JavaScript (index.js):
// index.js
import config from './config.json' with { type: 'json' };
console.log(config.version); // Output: '1.0.0'
The Classic Browser Method: Using fetch()
If you cannot use ES Modules or need to support older browsers, the standard way to load a JSON file is with the fetch() API. This method is asynchronous.
For example, you want to load a JSON file in a standard, non-module script.
Solution:
async function loadConfig() {
try {
const response = await fetch('./config.json');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const config = await response.json(); // This parses the JSON response body
console.log(config.version); // Output: '1.0.0'
} catch (error) {
console.error('Could not fetch config:', error);
}
}
loadConfig();
This approach is universal and works in any modern browser environment, but it requires handling the asynchronous nature of fetch().
The Classic Node.js Method: Using require()
In traditional Node.js projects that use the CommonJS module system (the default if "type": "module" is not set), you can import a JSON file directly using the require() function.
For example, you want to load a JSON file in a standard Node.js (CommonJS) environment.
Solution: Node.js's require function has built-in support for .json files. It will automatically read the file and parse it into a JavaScript object.
JavaScript (index.js):
// index.js
const config = require('./config.json');
console.log(config.version); // Output: '1.0.0'
console.log(config.api.url); // Output: 'https://api.example.com'
This is the simplest and most direct method for CommonJS-based Node.js projects.
Conclusion
The way you import a JSON file depends entirely on your project's environment and module system.
- For modern browsers and Node.js projects using ES Modules, the
import data from './file.json' with { type: 'json' }syntax is the recommended best practice. - For browser-based projects that do not use ES Modules, the standard approach is to use the
fetch()API and parse the response with.json(). - For Node.js projects using the traditional CommonJS module system, the simplest method is to use the
require('./file.json')function.