How to import JSON files in ES modules (Node.js)
- Published at
- Updated at
- Reading time
- 2min
The post was initially released in May 2021 when importing JSON in ECMAScript modules wasn't a straightforward task. I've kept this post up to date and am happy to say that we can mark the problem of importing JSON in Node.js modules as solved!
After quite a bit of back and forth, the current Node.js LTS (currently v22
) and future Node.js versions support JSON modules by using the JavaScript-native "import attributes".
Here's the quick tl;dr to import JSON in your module-based Node.js scripts.
// top-level JSON module import
import data from './data.json' with { type: 'json' };
// dynamic JSON module import
const { default: data } = await import("./data.json", {
with: {
type: "json",
},
});
That's it! ๐
If you're on a legacy Node.js version, here are also some "old school" approaches to import JSON files in Node.js modules.
The Node.js documentation advises to use the fs
module and do the work of reading the files and parsing them yourself.
import { readFile } from 'fs/promises';
const json = JSON.parse(
await readFile(
new URL('./some-file.json', import.meta.url)
)
);
The documentation also states that you can use createRequire
to load JSON files. This approach is the way Pawel advises in his blog post.
createRequire
allows you to construct a CommonJS require
function to use typical CommonJS features such as reading JSON in your Node.js ECMAScript modules.
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const data = require("./data.json");
And that's all! The legacy options never felt great, and I'm honestly relieved that we now have a standardized way to import JSON!
Join 5.9k readers and learn something new every week with Web Weekly.