To load a local JSON file cleanly in JavaScript and Node.js, use fetch() with await response.json() in browser/client JavaScript (served over HTTP/HTTPS rather than file://), and in Node.js use node:fs/promises (readFile + JSON.parse()) for runtime file loading or static ES module JSON imports (import data from "./file.json" with { type: "json" }) when the file path and structure are known at build/load time. Always validate the response or file read and wrap JSON.parse() / response.json() in proper error handling so malformed JSON or missing files fail predictably.
1. Loading a Local JSON File in Browser JavaScript (fetch)
In browser JavaScript, load a local JSON asset served by your web server or bundler using fetch(url), check response.ok, and parse with await response.json():
// Load a local JSON file served over HTTP/HTTPS in the browser
async function loadBrowserJson(url, { signal } = {}) {
if (typeof url !== "string" || url.trim().length === 0) {
throw new TypeError("Expected a non-empty JSON URL string.");
}
const response = await fetch(url, { signal });
if (!response.ok) {
throw new Error(`Failed to load JSON (${response.status} ${response.statusText}) from "${url}".`);
}
return response.json();
}
// Example usage:
(async () => {
try {
const config = await loadBrowserJson("/config/app-settings.json");
console.log(config);
} catch (err) {
console.error("Error loading JSON:", err);
}
})();
- Check
response.ok:fetch()only rejects on network failures—it still resolves on404or500HTTP responses unless you checkresponse.ok. - Avoid
file://URLs: Opening HTML files directly viafile://often blocksfetch()due to browser origin restrictions; run a local dev server instead.
2. Loading a Local JSON File at Runtime in Node.js (fs/promises + JSON.parse)
When reading a JSON file dynamically at runtime in Node.js—such as user-selected paths, config files, or data dumps—read the file as "utf8" using node:fs/promises and parse it with JSON.parse():
// Read and parse a local JSON file at runtime in Node.js
import { readFile } from "node:fs/promises";
import path from "node:path";
async function loadNodeJson(filePath) {
if (typeof filePath !== "string" || filePath.trim().length === 0) {
throw new TypeError("Expected filePath to be a non-empty string.");
}
const resolvedPath = path.resolve(filePath);
const rawText = await readFile(resolvedPath, "utf8");
try {
return JSON.parse(rawText);
} catch (err) {
throw new SyntaxError(`Invalid JSON in "${resolvedPath}": ${err.message}`);
}
}
// Example usage:
const usersData = await loadNodeJson("./data/users.json");
console.log(usersData);
- Resolve paths explicitly: Using
path.resolve()(ornew URL("./data.json", import.meta.url)in ES modules) avoids surprises relative to the current working directory. - Surface file path on parse errors: Wrapping
JSON.parse()lets you report which file had invalid syntax.
3. Importing Static JSON Modules in Node.js (with { type: "json" })
For static JSON files known ahead of time in ES modules, import them directly with a JSON import attribute (with { type: "json" }):
// Static ES module JSON import in Node.js
import packageMeta from "./package.json" with { type: "json" };
console.log(packageMeta.name);
- Static vs. dynamic loading: Static JSON imports are great for fixed metadata or build-time/startup constants, whereas
readFile()+JSON.parse()is better for runtime paths, large files, or files that may change while the process runs. - No
require("./file.json")in ESM: In ES module files (.mjsor"type": "module"),requireis not defined—usewith { type: "json" }orreadFile()instead.
TL;DR: In browser JavaScript, use await (await fetch(url)).json() after checking response.ok; in Node.js, use readFile(path, "utf8") + JSON.parse() from node:fs/promises for dynamic runtime reads, or import data from "./file.json" with { type: "json" } for static ES module imports.
