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:
In order to avoid adding
json-loader
in eachimport
you can add towebpack.config
this line:loaders: [
{ test: /\.json$/, loader: 'json-loader' },
// other loaders
]Then import
json
files like thisimport suburbs from '../suburbs.json';
Use
json-loader
directly in yourimport
, 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 theimport
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, specificallySome 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
JavaScript || or Operator with an Undefined Variable
Replace a String in a File with Nodejs
In Bootstrap Open Enlarge Image in Modal
Executing JavaScript Without a Browser
When to Use the Double Not (!!) Operator in JavaScript
Dot and Square Bracket Notation
Add Cors Header to an Http Request Using Ajax
Change Route Params Without Reloading in Angular 2
Convert an Image into Binary Data in JavaScript
How to Call a Parent Method from Child Class in JavaScript
Regex for Number with Decimals and Thousand Separator
Accessing the Content of Other Tabs in a Browser
Export Table from Database to CSV File
How Dangerous Is It in JavaScript, Really, to Assume Undefined Is Not Overwritten
Contain Form Within a Bootstrap Popover
Jslint Is Suddenly Reporting: Use the Function Form of "Use Strict"