Last updated: Mar 6, 2024
Reading timeยท6 min
If you need to import a JSON file in Node.js, click on the second subheading.
If you need to import a JSON file in TypeScript, check out my other article:
To import a JSON file in JavaScript:
type
attribute on the script tag is set to module
.import myJson from './example.json' assert {type: 'json'}
.Here is my index.html
file that has a script tag pointing to an index.js
module.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Hello world</div> <!-- ๐๏ธ type set to module --> <script type="module" src="index.js"></script> </body> </html>
Make sure the
type
attribute is set to module
because we are using the
ES6 Modules
syntax.
And here is how we would import a JSON file in our index.js
file.
import myJson from './example.json' assert {type: 'json'}; // ๐๏ธ { // name: 'Alice', // country: 'Austria', // tasks: [ 'develop', 'design', 'test' ], // age: 30 // } console.log(myJson.person); console.log(myJson.person.name); // ๐๏ธ "Alice" console.log(myJson.person.country); // ๐๏ธ "Austria"
Surprisingly, Firefox has been slower to implement this, however, Chrome and most other browsers should work.
If you get an error when using the assert
keyword (Uncaught SyntaxError:
unexpected token: 'assert'), try using with
instead.
import myJson from './example.json' with {type: 'json'}; // ๐๏ธ { // name: 'Alice', // country: 'Austria', // tasks: [ 'develop', 'design', 'test' ], // age: 30 // } console.log(myJson.person); console.log(myJson.person.name); // ๐๏ธ "Alice" console.log(myJson.person.country); // ๐๏ธ "Austria"
In March of 2023, the keyword
changed from assert
to with
.
// Before import myJson from './example.json' assert {type: 'json'}; // after import myJson from './example.json' with {type: 'json'};
However, browsers haven't had time to implement this. For compatibility with
existing implementations, the assert
keyword is still supported.
The code sample assumes that there is an example.json
file located in the same
directory.
{ "person": { "name": "Alice", "country": "Austria", "tasks": ["develop", "design", "test"], "age": 30 } }
The file structure in the example looks as follows.
my-project/ โโโ index.html โโโ index.js โโโ example.json
If I open the Console
tab in my Developer tools, I can see that the JSON file
has been imported successfully.
You can read more about why this is necessary in the Import assertions proposal page on GitHub.
In short, the import assertion proposal adds an inline syntax for module import statements.
This helps us avoid a scenario where a server responds with a different MIME type, causing code to be unexpectedly executed.
The assert {type: 'json'}
(or with {type: 'json'}
) syntax enables us to
specify that we are importing a JSON or similar module type that isn't going to
be executed.
If I remove the assert {type: 'json'}
(or with {type: 'json'}
) syntax from
the import statement, I'd get an error.
// โ๏ธ Error: Failed to load module script: Expected a JavaScript module script // but the server responded with a MIME type of "application/json". // Strict MIME type checking is enforced for module scripts per HTML spec. import myJson from './example.json';
You can read more about the import assertions proposal in this tc39 GitHub repository.
To import a JSON file in Node.js:
17.5
or more recent.type
property in your package.json
file is set to module
.import myJson from './example.json' assert {type: 'json'}
.17.5
because import assertions are valid syntax starting version 17.5
.The type
property in your package.json
has to be set to module
.
{ "type": "module", // ... rest }
Now we can import a JSON file using an import assertion.
// ๐๏ธ using assert import myJson from './example.json' assert {type: 'json'}; // ๐๏ธ { // name: 'Alice', // country: 'Austria', // tasks: [ 'develop', 'design', 'test' ], // age: 30 // } console.log(myJson.person); console.log(myJson.person.name); // ๐๏ธ "Alice" console.log(myJson.person.country); // ๐๏ธ "Austria"
NOTE: if you get an error when using the assert
keyword, use the with
keyword instead.
// ๐๏ธ using with import myJson from './example.json' with {type: 'json'}; // ๐๏ธ { // name: 'Alice', // country: 'Austria', // tasks: [ 'develop', 'design', 'test' ], // age: 30 // } console.log(myJson.person); console.log(myJson.person.name); // ๐๏ธ "Alice" console.log(myJson.person.country); // ๐๏ธ "Austria"
The code snippet above assumes that there is an example.json
file located in
the same directory.
{ "person": { "name": "Alice", "country": "Austria", "tasks": ["develop", "design", "test"], "age": 30 } }
Here is the output from running the index.js
file.
In March of 2023, the keyword
changed from assert
to with
.
// Before import myJson from './example.json' assert {type: 'json'}; // after import myJson from './example.json' with {type: 'json'};
However, browsers and the Node.js team haven't had time to implement this. For
compatibility with existing implementations, the assert
keyword is still
supported.
You can read more about the assert syntax on the Import assertions proposal page.
The import assertion proposal adds an inline syntax for module import statements.
This helps us avoid a scenario where a server responds with a different MIME type, causing code to be unexpectedly executed.
The assert {type: 'json'}
(or with {type: 'json'}
) syntax enables us to
specify that we are importing a JSON or similar module type that isn't going to
be executed.
If I remove the assert {type: 'json'}
(or with {type: 'json'}
) syntax from
the import statement, I'd get an error.
// โ๏ธ TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]: // Module "/bobbyhadz-js/example.json" needs an // import assertion of type "json" import myJson from './example.json';
You can read more about the import assertions proposal in this tc39 GitHub repository.
Alternatively, you can use the fs
module to open the .json
file in Node.js.
fs
moduleHere is an example of
using the fs
module to import a JSON
file when using Node.js.
This is the example.json
file that we'll be importing.
{ "person": { "name": "Alice", "country": "Austria", "tasks": ["develop", "design", "test"], "age": 30 } }
And this is how we can import and use the JSON file in an index.js
file.
import fs from 'fs'; // ๐๏ธ if you use CommonJS imports, use this instead // const fs = require('fs'); const result = JSON.parse(fs.readFileSync('./example.json')); // ๐๏ธ { // name: 'Alice', // country: 'Austria', // tasks: [ 'develop', 'design', 'test' ], // age: 30 // } console.log(result); console.log(result.person.name); // ๐๏ธ "Alice" console.log(result.person.country); // ๐๏ธ "Austria"
The code sample assumes that the example.json
file is placed in the same
directory as the index.js
file.
We used the readFileSync
method to read the file synchronously and then used
the JSON.parse
method to parse the JSON string into a native JavaScript
object.
If you use the CommonJS require()
syntax, use the following import statement
instead.
const fs = require('fs'); const result = JSON.parse(fs.readFileSync('./example.json')); // ๐๏ธ { // name: 'Alice', // country: 'Austria', // tasks: [ 'develop', 'design', 'test' ], // age: 30 // } console.log(result); console.log(result.person.name); // ๐๏ธ "Alice" console.log(result.person.country); // ๐๏ธ "Austria"
The code sample achieves the same result but uses the require()
syntax to
import the fs
module.
You can also use the await
keyword to await a promise when importing the JSON
file in more recent versions of Node.js.
import fs from 'fs/promises'; const result = JSON.parse(await fs.readFile('./example.json')); // ๐๏ธ { // name: 'Alice', // country: 'Austria', // tasks: [ 'develop', 'design', 'test' ], // age: 30 // } console.log(result); console.log(result.person.name); // ๐๏ธ "Alice" console.log(result.person.country); // ๐๏ธ "Austria"
However, note that
using await
outside an async
function
is only available starting with Node.js version 14.8+.
If you need to import a JSON file in TypeScript, check out my other article: How to Import a JSON file in TypeScript.
You can learn more about the related topics by checking out the following tutorials: