How to import a JSON file in ECMAScript 6?

Importing JSON using ES modules was submitted as feature to TC39 in mid 2020, and is (at the time of this edit) in stage 3, which is the last stage before being accepted in to the spec (see https://github.com/tc39/proposal-json-modules for more details). Once landed, you will be able to use it as:

import someName from "./some/path/to/your/file.json";

Where someName is effectively the name of the variable for the JS object described by the JSON data. (And of course, note that this imports JavaScript from a JSON source, it does not “import JSON”).

If you’re using a modern enough bundler (like esbuild or the like) or you’re using a recent enough transpiler (like babel) then you can already use this syntax without having to worry about support.

Alternatively, if you have the luxury of ownership of JSON files you can also turn your JSON into valid JS files with a minimum of extra code:

config.js

export default
{
  // my json here...
}

then…

import config from '../config.js'

does not allow import of existing .json files, but does a job.

Leave a Comment