[json] How to import a JSON file in ECMAScript 6?

How can I access a JSON file in ECMAScript 6?

The following doesn't work:

import config from '../config.json'

This works fine if I try to import a JavaScript file.

This question is related to json import ecmascript-6

The answer is


Depending on your build tooling and the data structure within the JSON file, it may require importing the default.

import { default as config } from '../config.json';

e.g. usage within Next.js


I used it installing the plugin "babel-plugin-inline-json-import" and then in .balberc add the plugin.

  1. Install plugin

    npm install --save-dev babel-plugin-inline-json-import

  2. Config plugin in babelrc

    "plugin": [ "inline-json-import" ]

And this is the code where I use it

import es from './es.json'
import en from './en.json'

export const dictionary = { es, en }

I'm using

  • vuejs, version: 2.6.12
  • vuex, version: 3.6.0
  • vuex-i18n, version: 1.13.1.

My solution is:

messages.js:

import Vue from 'vue'
import Vuex from 'vuex';
import vuexI18n from 'vuex-i18n';
import translationsPl from './messages_pl'
import translationsEn from './messages_en'

Vue.use(Vuex);

export const messages = new Vuex.Store();

Vue.use(vuexI18n.plugin, messages);

Vue.i18n.add('en', translationsEn);
Vue.i18n.add('pl', translationsPl);

Vue.i18n.set('pl');

messages_pl.json:

{
    "loadingSpinner.text:"Ladowanie..."
}

messages_en.json:

{
    "loadingSpinner.default.text":"Loading..."
}

majn.js

import {messages} from './i18n/messages'
Vue.use(messages);

For NodeJS v12 and above, --experimental-json-modules would do the trick, without any help from babel.

https://nodejs.org/docs/latest-v14.x/api/esm.html#esm_experimental_json_modules

But it is imported in commonjs form, so import { a, b } from 'c.json' is not yet supported.

But you can do:

import c from 'c.json';
const { a, b } = c;

Simply do this:

import * as importedConfig from '../config.json';

Then use it like the following:

const config = importedConfig.default;

importing JSON files are still experimental. It can be supported via the below flag.

--experimental-json-modules

otherwise you can load your JSON file relative to import.meta.url with fs directly:-

import { readFile } from 'fs/promises';
const config = JSON.parse(await readFile(new URL('../config.json', import.meta.url)));

you can also use module.createRequire()

import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const config = require('../config.json');

In TypeScript or using Babel, you can import json file in your code.

// Babel

import * as data from './example.json';
const word = data.name;
console.log(word); // output 'testing'

Reference: https://hackernoon.com/import-json-into-typescript-8d465beded79


A bit late, but I just stumbled across the same problem while trying to provide analytics for my web app that involved sending app version based on the package.json version.

Configuration is as follows: React + Redux, Webpack 3.5.6

The json-loader isn't doing much since Webpack 2+, so after some fiddling with it, I ended up removing it.

The solution that actually worked for me, was simply using fetch. While this will most probably enforce some code changes to adapt to the async approach, it worked perfectly, especially given the fact that fetch will offer json decoding on the fly.

So here it is:

  fetch('../../package.json')
  .then(resp => resp.json())
  .then((packageJson) => {
    console.log(packageJson.version);
  });

Do keep in mind, that since we're talking about package.json specifically here, the file will not usually come bundled in your production build (or even dev for that matter), so you will have to use the CopyWebpackPlugin to have access to it when using fetch.


In a browser with fetch (basically all of them now):

At the moment, we can't import files with a JSON mime type, only files with a JavaScript mime type. It might be a feature added in the future (official discussion).

fetch('./file.json')
  .then(response => response.json())
  .then(obj => console.log(obj))

In Node.js v13.2+:

It currently requires the --experimental-json-modules flag, otherwise it isn't supported by default.

Try running

node --input-type module --experimental-json-modules --eval "import obj from './file.json'; console.log(obj)"

and see the obj content outputted to console.


Adding to the other answers, in Node.js it is possible to use require to read JSON files even inside ES modules. I found this to be especially useful when reading files inside other packages, because it takes advantage of Node's own module resolution strategy to locate the file.

require in an ES module must be first created with createRequire.

Here is a complete example:

import { createRequire } from 'module';

const require = createRequire(import.meta.url);
const packageJson = require('typescript/package.json');
console.log(`You have TypeScript version ${packageJson.version} installed.`);

In a project with TypeScript installed, the code above will read and print the TypeScript version number from package.json.


If you're using node you can:

const fs = require('fs');

const { config } = JSON.parse(fs.readFileSync('../config.json', 'utf8')) // May be incorrect, haven't used fs in a long time

OR

const evaluation = require('../config.json');
// evaluation will then contain all props, so evaluation.config
// or you could use:
const { config } = require('../config.json');

Else:

// config.js
{
// json object here
}

// script.js

import { config } from '../config.js';

OR

import * from '../config.json'

Unfortunately ES6/ES2015 doesn't support loading JSON via the module import syntax. But...

There are many ways you can do it. Depending on your needs you can either look into how to read files in JavaScript (window.FileReader could be an option if you're running in the browser) or use some other loaders as described in other questions (assuming you are using NodeJS).

IMO simplest way is probably to just put the JSON as a JS object into an ES6 module and export it. That way you can just import it where you need it.

Also worth noting if you're using Webpack, importing of JSON files will work by default (since webpack >= v2.0.0).

import config from '../config.json';

I'm using babel+browserify and I have a JSON file in a directory ./i18n/locale-en.json with translations namespace (to be used with ngTranslate).

Without having to export anything from the JSON file (which btw is not possible), I could make a default import of its content with this syntax:

import translationsJSON from './i18n/locale-en';

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to import

Import functions from another js file. Javascript The difference between "require(x)" and "import x" pytest cannot import module while python can How to import an Excel file into SQL Server? When should I use curly braces for ES6 import? How to import a JSON file in ECMAScript 6? Python: Importing urllib.quote importing external ".txt" file in python beyond top level package error in relative import Reading tab-delimited file with Pandas - works on Windows, but not on Mac

Examples related to ecmascript-6

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 where is create-react-app webpack config and files? Can (a== 1 && a ==2 && a==3) ever evaluate to true? How do I fix "Expected to return a value at the end of arrow function" warning? Enums in Javascript with ES6 Home does not contain an export named Home How to scroll to an element? How to update nested state properties in React eslint: error Parsing error: The keyword 'const' is reserved Node.js ES6 classes with require