Reading a JSON file in JavaScript is a fundamental skill for web developers. JSON (JavaScript Object Notation) files are commonly used for data interchange in web development. This guide teaches you how to read a JSON file in JavaScript, providing step-by-step instructions and examples to help you effectively handle JSON data in your projects.
Methods to read JSON files in JS are :
- With Fetch API.
- With the Import Statement.
- Using Required Module.
Furthermore, the above methods will help you import JSON files in JS without inconvenience. This blog is your best guide if you don’t know how to read a JSON file in JavaScript.
Table of Contents
Reading JSON in JS
As discussed above, JSON stands for JavaScript Object Notation and is syntactically identical to the code for making objects in JavaScript. Furthermore, you can also convert JavaScript objects to JSON. Both machines and humans can read JSON, a data exchange file format. Before JSON, XML was used to keep data, but it was not easy to read and understand for humans and was not as user-friendly as JSON. JSON can be accessed quickly, and it contains only text. The data stored in a key-value pair format is identical to objects in JavaScript. The syntax for a key-value pair is to write it within double quotes, divided by a colon, for example :
“age”: “24”
To clarify how these features work, see JavaScript in Visual Studio Code.
How to Read a JSON File in JavaScript? Different Methods
This section will discuss the methods for how to read a JSON file in JavaScript. Without further ado, let’s discuss these methods.
Method 1: With the Fetch API
The first way to read JSON files in JavaScript is to use the fetch API. It uses identical syntax for local files and one uploaded to a server, but the URL is distinct. For example, let’s say we have a local JSON file inside our project folder named example.json that stores the following data:
<!–./example.JSON–>
{
“id”: 3,
“title”: “Hello World”,
“completed”: false
}
Now, we will use the Fetch API method. For instance:
<!–./index.js–>
fetch(‘./example.json’)
.then((response) => response.json())
.then((json) => console.log(json));
We have successfully been able to read the above JSON file, but when you use this code in a browser, you will get a CORS error as the file is not present on a server. We will ensure the file is on a local server to avoid this issue. The syntax will be identical, and we have to pass the full URL of the JSON file. For instance:
<!–./index.js–>
fetch(‘https://server.com/example.json’)
.then((response) => response.json())
.then((json) => console.log(json));
You can use this method to read your JSON file from an external server or a local file.
Method 2: With the Import Statement
The second method in JavaScript to read JSON files is to apply the import statement. We have a JSON file named example.json that has the following data :
{
“id”: 2,
“name”: “Aaron Ramsey”,
“isActive”: true
}
Before using the import statement, add a <script> tag with the type attribute set to “module”(it will import the JSON file). For instance:
<body>
<div>Importing JSON</div>
<script type=”module” src=”index.js”></script>
</body>
Now, in the index.js file, we will use the import statement. For instance :
import json from ‘./example.json’ assert {type: ‘json’};
console.log(json.name); // Aaron Ramsey
console.log(json.isActive); // true
An assert statement tells the browser that you are waiting for a MIME type of “application/json” from the import statement. You will face an error if you don’t use an assert statement. Additionally, if you get an error from the assert statement, then use the with statement. For instance:
import json from ‘./example.json’ with {type: ‘json’};
Method 3: Using Required Module
Before understanding the required module, let’s assume we have a data.json file with the following data:
{
“student”: [
{
“reg-num”:”5″,
“name”: “Michael”,
“lastname”: “Stinson”
},
{
“reg-num”:”6″,
“name”: “Andrew”,
“lastname”: “Thompson”
}
]
}
Now, we will use the required module in the JavaScript file like this:
const dataJson = require(‘data.json’);
console.log(typeof dataJson);
console.log(dataJson);
In the above code, we have started a variable dataJson with the help of the require() module. The needed module is an integral function that incorporates extrinsic modules in separate files. Therefore, the require() module has done its job by involving the external data.json file, which we can read now. Afterwards, console.log(dataJson) shows the data present within the JSON file. These three methods give a detailed guide on how to read a JSON file in JavaScript.
FAQs
How to edit a JSON file?
Editing a JSON file is simple and easy. Open any code editor like VS Code or Notepad and edit the JSON file according to your needs.
How to import a JSON file in JavaScript?
You can use the import statement to import a JSON file in JavaScript and Typescript. While importing, state the 'json' assertion type. For instance, use the following code: import json from './example.json' assert {type: 'json'};
What is the full form of JSON?
JSON stands for JavaScript Object Notation and is syntactically identical to the code for making objects in JavaScript. Both machines and humans can read JSON, a data exchange file format.
Why is JSON used?
JSON is used to accumulate temporary data. It is preferred because it can be accessed quickly and contains only text.
Conclusion
In conclusion, we learned how to read a JSON file in JavaScript using the above methods. These are the only methods you need to read a JSON file. The fetch API is the best method to read your JSON file from an external or local server. You can also import JSON files in React or any other JavaScript framework with the help of import statements.
JSON is used to convert Python dictionaries to JSON. Moreover, JavaScript has many applications through which you can practice and learn anything. For example, you can use JavaScript to change the background color for your web projects and use it with other languages.
See Also: How To Convert JavaScript To TypeScript? Step-By-Step Guide