How to import a JSON file in ECMAScript 6?

JsonImportEcmascript 6

Json Problem Overview


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.

Json Solutions


Solution 1 - 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

Solution 2 - Json

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.

Solution 3 - 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';

Solution 4 - Json

If you're using node you can:

const fs = require('fs');

const { config } = JSON.parse(fs.readFileSync('../config.json'));

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'

Solution 5 - 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';

Solution 6 - Json

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

Solution 7 - Json

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.

Solution 8 - Json

Thanks to all the people who proposed and implemented JSON modules and Import Assertions. Since Chrome 91, you can import JSON directly, for example:

// test.json
{
    "hello": "world"
}

// Static Import
import json from "./test.json" assert { type: "json" };
console.log(json.hello);

// Dynamic Import
const { default: json } = await import("./test.json", { assert: { type: "json" } });
console.log(json.hello);

// Dynamic Import
import("./test.json", { assert: { type: "json" } })
  .then(module => console.log(module.default.hello));

Note: other browsers may not yet implement this feature at the moment.

Solution 9 - Json

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.

Solution 10 - Json

Simply do this:

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

Then use it like the following:

const config = importedConfig.default;

Solution 11 - Json

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;

Solution 12 - Json

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.

Solution 13 - Json

import data from "./resource.json” is possible in Chrome 91. JSON modules are now supported. This allows developers to statically import JSON instead of relying on the fetch() function which dynamically retrieves it.

https://www.stefanjudis.com/snippets/how-to-import-json-files-in-es-modules/

Solution 14 - Json

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

Solution 15 - Json

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 }

Solution 16 - Json

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:"Ładowanie..."
}

messages_en.json:

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

majn.js

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

Solution 17 - Json

A more elegant solution is to use the CommonJS require function

createRequire construct a CommonJS require function so that you can use typical CommonJS features such as reading JSON

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

Solution 18 - Json

As said by Azad, the correct answer is to load the file with fs.readFileSync() (or any of the asynchronous variants such as fs.readFile with callback or fs.promises.readFile with promises/await, then parse the JSON with JSON.parse()

const packageJsonRaw = fs.readFileSync('location/to/package.json' ) 
const packageJson = JSON.parse(packageJsonRaw )

Webpack/Babel options are not practical unless you are already using that set up.

Solution 19 - Json

The file structure with the json extension is used to transfer data, the json file data can be retrieved locally by sending a request using the fetch command.

In the following example, the data of the count.json file is received

// count.json

fetch("./count.json") 
.then((response) => { return response.json(); }) 
.then((data) => console.log(data));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNikita JajodiaView Question on Stackoverflow
Solution 1 - JsonwilliamliView Answer on Stackoverflow
Solution 2 - JsonGilbertView Answer on Stackoverflow
Solution 3 - JsonSimoneView Answer on Stackoverflow
Solution 4 - JsonAnonymous User 2903View Answer on Stackoverflow
Solution 5 - JsonFrancisco NetoView Answer on Stackoverflow
Solution 6 - JsonPat MigliaccioView Answer on Stackoverflow
Solution 7 - JsontrusktrView Answer on Stackoverflow
Solution 8 - JsonJackie HanView Answer on Stackoverflow
Solution 9 - JsonAvram TudorView Answer on Stackoverflow
Solution 10 - JsonnewwebdevView Answer on Stackoverflow
Solution 11 - JsonaGueguView Answer on Stackoverflow
Solution 12 - JsonGOTO 0View Answer on Stackoverflow
Solution 13 - JsonLudovic AubertView Answer on Stackoverflow
Solution 14 - JsonazadView Answer on Stackoverflow
Solution 15 - JsonramseslsView Answer on Stackoverflow
Solution 16 - JsonPiotr ŻakView Answer on Stackoverflow
Solution 17 - JsonPascalView Answer on Stackoverflow
Solution 18 - JsonRobert SandifordView Answer on Stackoverflow
Solution 19 - JsonmeysamView Answer on Stackoverflow