Es6 Modules Implementation, How to Load a JSON File

ES6 modules implementation, how to load a json file

First of all you need to install json-loader:

npm i json-loader --save-dev

Then, there are two ways how you can use it:

  1. In order to avoid adding json-loader in each import you can add to webpack.config this line:

    loaders: [
    { test: /\.json$/, loader: 'json-loader' },
    // other loaders
    ]

    Then import json files like this

    import suburbs from '../suburbs.json';
  2. Use json-loader directly in your import, as in your example:

    import suburbs from 'json!../suburbs.json';

Note:
In webpack 2.* instead of keyword loaders need to use rules.,

also webpack 2.* uses json-loader by default

*.json files are now supported without the json-loader. You may still use it. It's not a breaking change.

v2.1.0-beta.28

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.

Import '.json' extension in ES6 Node.js throws an error

From Node.js version 17.5.0 onward, importing a JSON file is possible using Import Assertions:

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

const {
name,
version
} = packageFile;
  • assert { type: "json" } is mandatory
  • Destructuring such as { name, version } is not possible in the import declaration directly
  • The contents of the JSON file are exported as a default export, so they need to be imported from default.

The dynamic import version looks like this:

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

Since import assertions and JSON modules have only recently promoted to stage 3, older versions of Node.js might have supported an older syntax.
According to the compatibility tables on MDN for import declarations and dynamic import, older versions of Node.js (16.0.0 – 16.14.0 and 17.0.0 – 17.4.0) had varying support:

  • These versions required the --experimental-json-modules flag:

    node --experimental-json-modules about.js
  • Some versions did not support import assertions on dynamic import

  • Some versions did not support the "json" type, specifically

  • Some versions relied on an older proposal which did not specify the assert syntax yet

Does the ES modules implementation support importing JSON files?

I've found in the Node.js ES Modules docs that currently importing JSON is only supported in the CommonJS mode and the flag --experimental-json-modules is required for importing JSON files in ES modules.

Assuming an index.mjs with

import packageConfig from './package.json';

The --experimental-json-modules flag is needed for the module to work.

node index.mjs # fails
node --experimental-json-modules index.mjs # works

Is there a way to read a local JSON array in ES6?

It's about your import statement.

while handling JSON file in js, it's been turned into a js that export data.

[1,2,3]

with

import data from "./data.json"
console.log(data) // [1,2,3]

with

import * as data from "./data.json"
console.log(data) // {0:1,1:2,2:3, default:[1,2,3]}

as it's been treated as ES module, so you import an object instead of the array itself, so the map function will be undefined, as it's just a plain object.



Here's why

Webpack load JSON with json-loader, which is officially supported that you won't need to configure yourself, and the json-loader will handle JSON files by stringify it and concat with module.exports=, source code here,
so the JSON will be in js like

module.exports = [0,1,2]

and as the module.exports object itself will be imported as default export in an ESM file, and all objects fields will be export as others, so you will get an ESM object while doing import * as data from "./data.json"

Of cause if you are using a different JSON loader the value will be different, but the error is what you meet.

Load local JSON file into variable

If you pasted your object into content.json directly, it is invalid JSON. JSON keys and values must be wrapped in double quotes (" not ') unless the value is numeric, boolean, null, or composite (array or object). JSON cannot contain functions or undefined values. Below is your object as valid JSON.

{
"id": "whatever",
"name": "start",
"children": [
{
"id": "0.9685",
"name": " contents:queue"
},
{
"id": "0.79281",
"name": " contents:mqq_error"
}
]
}

You also had an extra }.

Import JSON file in React

One nice way (without adding a fake .js extension which is for code not for data and configs) is to use json-loader module. If you have used create-react-app to scaffold your project, the module is already included, you just need to import your json:

import Profile from './components/profile';

This answer explains more.



Related Topics



Leave a reply



Submit