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!

TL;DR โ€” import JSON with ECMAScript import attributes

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.

Legacy option 1: Read and parse JSON files yourself

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)
  )
);

Legacy option 2: Leverage the CommonJS require function to load JSON files

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!

If you enjoyed this article...

Join 5.9k readers and learn something new every week with Web Weekly.

Web Weekly โ€” Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles

OSZAR »