How To Read Json File In Javascript

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is a popular choice when transferring data between a server and a client because it is easy to handle and understand. In this blog post, we will learn how to read a JSON file in JavaScript.

Reading JSON File

To read a JSON file in JavaScript, we can use the Fetch API, which allows us to request and fetch resources across the network. The Fetch API returns a Promise that resolves to the Response of the request, whether it is successful or not.

Using the Fetch API

Let’s assume we have a JSON file called data.json with the following content:

{
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}
    

To read this JSON file and display the data in the console, we can use the following code:

fetch('data.json')
    .then(response => response.json())
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error('Error fetching JSON file:', error);
    });

In the code above, we use the fetch() function to request the data from the JSON file. We then get the response and convert it to JSON using the response.json() method. Finally, we use the data in the then() block and log it to the console. If there is any error while fetching the JSON file, it will be caught and logged in the catch() block.

Handling JSON Data

Once we have the JSON data, we can parse and use it as needed. For example, let’s say we want to display the name and age of the person in the JSON file. We can modify the previous code as follows:

fetch('data.json')
    .then(response => response.json())
    .then(data => {
        console.log(`Name: ${data.name}, Age: ${data.age}`);
    })
    .catch(error => {
        console.error('Error fetching JSON file:', error);
    });

This would output Name: John Doe, Age: 30 in the console.

Conclusion

In this blog post, we learned how to read a JSON file in JavaScript using the Fetch API. We requested the JSON data, converted it to a JavaScript object, and then used the data as needed. Fetch API makes it easy to request and handle JSON files, making it an essential tool for modern web development.