Node.jsでJSONがimportで読み込めないときの対処法

Node.jsでJSONをimportでエラー

Node.jsを使用しているとpackage.jsonなどのJSONファイルからデータを取得したいことがある。

しかし、普通に以下のようにimportでJSONを読み込もうとしてもエラーが出て読み込めない。

import data from './foo.json'

console.log(data)
$ node index.js
node:internal/errors:491
    ErrorCaptureStackTrace(err);
    ^

TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]: Module "file:///Users/iwbjp/foo.json" needs an import assertion of type "json"

理由はエラー文に書かれている通り、JSON型のimport assertionが必要だからです。

よって以下のようにassertでjsonを指定すれば読み込めるようになります。

import data from './foo.json' assert { type: 'json' }

console.log(data)
$ node index.js
{ foo: 123 }
(node:27672) ExperimentalWarning: Importing JSON modules is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)

ただし、JSONモジュールのインポートは実験的な(Experimental)機能なので、これもエラーは出ませんが警告は出てしまいます。

もし警告すら表示させたくない場合はfs.promisesからreadFileをimportして読み込んでください。

import { readFile } from 'fs/promises'

const json = JSON.parse(await readFile('./foo.json'))
console.log(json)

JavaScriptと同様にJSONも直接importだけを使って読み込みたくなりますが、実験的な機能である以上は将来的には前者のやり方は使用できなくなる可能性があります。

そのため、なるべく後者のfs.promisesからreadFileをimportして読み込むやる方をオススメします。