- How to Read a JSON File in JavaScript – Reading JSON in JS
- How to Read a JSON File in JavaScript with the Fetch API
- How to Read a JSON file in JavaScript with the Import Statement
- Wrapping Up
- Javascript loading json file
- # Table of Contents
- # Import a JSON file in the Browser
- # Import a JSON file in Node.js
- # Import a JSON file in Node.js with the fs module
- # Additional Resources
How to Read a JSON File in JavaScript – Reading JSON in JS
Joel Olawanle
When fetching data from external sources or servers, you need to make sure that the data returned is in JSON format. Then you can consume the data within your application.
In some situations, when you’re working locally or when you upload the data file to a server, we might want to read these JSON data from a file.
We’ll learn how to do that in this tutorial.
How to Read a JSON File in JavaScript with the Fetch API
One standard method we can use to read a JSON file (either a local file or one uploaded to a server) is with the Fetch API. It uses the same syntax for both. The only difference would be the URL.
For example, suppose we have a local file within our project’s folder named data.json that contains the following JSON data:
We can now read this file in JavaScript using the Fetch API method:
fetch('./data.json') .then((response) => response.json()) .then((json) => console.log(json));
In the above, we have been able to read a local JSON file. But unfortunately, when we run this in a browser, we might get the following CORS error because our file is not on a server:
To fix this, we will make sure our JSON file is on a local or remote server. If we use the Live server on our IDE, we won’t get this error. But when we load our file directly, we will get this error.
As I said earlier, suppose we have this JSON file on a remote server and are trying to read this file in JavaScript. The same syntax will work:
fetch('https://server.com/data.json') .then((response) => response.json()) .then((json) => console.log(json));
The fetch API is the preferable method to use when we want to read a JSON file either from an external server or local file into our JavaScript file.
How to Read a JSON file in JavaScript with the Import Statement
Another method we can use aside from making an HTTP request is the import statement. This method has a few complications, but we will address them all.
Just like in the previous section, suppose we have our JSON file that holds user data, such as user.json :
We can read this JSON data in JavaScript using the import statement this way:
import data from './data.json'; console.log(data);
Unfortunately, this will throw an error saying we cannot use the import statement outside a module. This is a standard error when we try to use the import statement in a regular JavaScript file, especially for developers who are new to JavaScript.
To fix this, we can add the type=»module» script tag in our HTML file where we referenced the JavaScript file, like this:
When we do this, we’ll still get another error:
To fix this error, we need to add the file type of JSON to the import statement, and then we’ll be able to read our JSON file in JavaScript:
import data from './data.json' assert < type: 'json' >; console.log(data);
This works perfectly as long as we run our files on a local or remote server. But suppose we run this locally – then we would get the CORS error.
Wrapping Up
In this article, we have learned how to read a JSON file in JavaScript and the possible errors we might encounter when using each method.
It’s best to use the fetch API method when you want to make an HTTP request. For example, suppose we are fetching data from a mock JSON file which we will eventually pull from an API.
Still, in a situation where we don’t need to use an HTTP request, we could use the import statement. We can use the import statement when we use a library like React, Vue, and so on which has to do with modules. This means we won’t need to add the type of module, and also, we won’t need to add the type of file.
Neither method requires you to install a package or use a library as they are inbuilt. Choosing which method to use is totally up to you.
But a quick tip that differentiates these methods is that the Fetch API reads a JSON file in JavaScript by sending an HTTP request, while the import statement does not require any HTTP request but rather works like every other import we make.
Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.
Javascript loading json file
Last updated: Jan 14, 2023
Reading time · 6 min
# Table of Contents
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:
# Import a JSON file in the Browser
To import a JSON file in JavaScript:
- Make sure the type attribute on the script tag is set to module .
- Use an import assertion to import the JSON file.
- For example, import myJson from ‘./example.json’ assert .
Here is my index.html file that has a script tag pointing to an index.js module.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> div id="box">Hello worlddiv> 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.
Copied!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"
If you get an error when using the assert keyword, try using with instead.
Copied!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 .
Copied!// 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.
Copied!"person": "name": "Alice", "country": "Austria", "tasks": ["develop", "design", "test"], "age": 30 > >
The file structure in the example looks as follows.
Copied!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.
The syntax was introduced for improved security when importing JSON modules and similar module types which cannot execute code.
This helps us avoid a scenario where a server responds with a different MIME type, causing code to be unexpectedly executed.
The assert (or with ) 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 (or with ) syntax from the import statement, I’d get an error.
Copied!// ⛔️ 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.
# Import a JSON file in Node.js
To import a JSON file in Node.js:
- Make sure you are running Node.js version 17.5 or more recent.
- Make sure the type property in your package.json file is set to module .
- Use an import assertion to import the JSON file.
- For example, import myJson from ‘./example.json’ assert .
Make sure your Node.js version is at least 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 .
Copied!"type": "module", // . rest >
Now we can import a JSON file using an import assertion.
Copied!// 👇️ 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.
Copied!// 👇️ 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.
Copied!"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 .
Copied!// 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.
The syntax was introduced for improved security when importing JSON modules and similar module types which cannot execute code.
This helps us avoid a scenario where a server responds with a different MIME type, causing code to be unexpectedly executed.
The assert (or with ) 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 (or with ) syntax from the import statement, I’d get an error.
Copied!// ⛔️ 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.
# Import a JSON file in Node.js with the fs module
Here 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.
Copied!"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.
Copied!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.
Copied!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.
Copied!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.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.