Categories
Node.js Quick Tips Quick Tips

Import JSON in ES modules

2 min read

This blog post is part of What’s new in Node.js core? March 2022 edition.

We’ve had really good ECMAScript (ES) module support in Node.js for a while, but up until now we’ve had to do messy little workarounds to import JSON files. The background on why is a blog post in itself, but the good news is that we can now import JSON modules in Node.js without an experimental flag.

This recently landed in the v17 (Current) release line, and should soon be backported to the v16 (Active LTS) release line.

Contributed by Antoine du Hamel and Geoffrey Booth

Example A: Static import with JSON import assertion

import packageJsonExample1 from "./package.json" assert { type: "json" };

console.log({ packageJsonExample1 });

Example B: Dynamic import with JSON import assertion

const packageJsonExample2 = await import("./package.json", {
  assert: { type: "json" },
});

console.log({ "packageJsonExample2.default": packageJsonExample2.default });

Support in Node.js

  • JSON modules added (experimental flag): v12.9.0
  • JSON import assertions added: v17.1.0
  • JSON import assertions backported: v16.14.0
  • JSON modules unflagged: v17.5.0 (with import assertion syntax only)

For versions of Node.js < v17.5.0 you need to use the --experimental-json-modules flag to use JSON imports in ES modules. If you want to try JSON imports with the import assertion syntax in Node.js v16 you’ll need to be running >= v16.14.0 and pass the experimental flag.

JSON imports are also supported by Deno and Chrome.

When can you use it in production?

The unflagging of JSON imports is likely to be backported in the next v16 (Active LTS) minor release (v16.15.0), currently scheduled for May 2022.

It will be in v18 — initial release 19 Apr 2022, Active LTS starts 25 Oct 2022.

Antoine du Hamel — co-contributor of this feature — gave a talk about it at Node Congress 2022: The Road to JSON Import Support in Node.js.

There’s some good background on import assertions in this V8 blog post.

Leave a Reply

Your email address will not be published. Required fields are marked *