Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to read json file in JavaScript

In this blog post, we're going to learn how to read JSON files in JavaScript. JSON, which stands for 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. Although it is derived from JavaScript, JSON is language-independent, so you can use it with almost any programming language.

Imagine you're trying to store information about a list of books, along with their authors and publication dates. Instead of using a database, you might decide to store this data in a simple text file, and JSON is a perfect format for this job. Here's an example of how the data for our books might look like in JSON format:

[
  {
    "title": "To Kill a Mockingbird",
    "author": "Harper Lee",
    "publicationDate": "1960-07-11"
  },
  {
    "title": "1984",
    "author": "George Orwell",
    "publicationDate": "1949-06-08"
  },
  {
    "title": "The Catcher in the Rye",
    "author": "J.D. Salinger",
    "publicationDate": "1951-07-16"
  }
]

When working with JSON files in JavaScript, there are two main steps involved:

  1. Reading the JSON file and converting it into a JavaScript object
  2. Accessing the data stored in the JavaScript object

In this tutorial, we'll cover both of these steps and provide practical examples along the way.

Reading a JSON file and converting it into a JavaScript object

There are several ways to read a JSON file in JavaScript, but one of the most common methods is to use the fetch() function. The fetch() function allows you to make network requests, such as downloading a file or making an API call, and it returns a Promise that resolves to the Response object representing the response to the request.

Here's a basic example of how to use the fetch() function to read a JSON file:

fetch('path/to/your/json/file.json')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error fetching JSON:', error));

In this example, we're fetching a JSON file located at path/to/your/json/file.json. The fetch() function returns a Promise, which we can use to handle the response once it's available. Once the Promise resolves, we can use the json() method to convert the response into a JavaScript object, which we can then work with.

Let's break down the code step-by-step:

  1. We call the fetch() function with the URL to our JSON file as the argument.
  2. The fetch() function returns a Promise, so we use the then() method to handle the response once it's available. The then() method takes a function as its argument, which it calls with the resolved response.
  3. We take the response and call its json() method, which also returns a Promise. This Promise resolves to the JavaScript object containing the data from our JSON file.
  4. We use another then() method to handle the resolved JavaScript object, which we can now work with. In this example, we're simply logging the object to the console, but in a real application, you might use this data to update your UI or perform some other action.
  5. If there's an error fetching the JSON file or parsing the response, we catch it using the catch() method and log the error to the console.

Accessing the data stored in the JavaScript object

Once you have the JavaScript object containing the data from your JSON file, you can access its properties and values just like you would with any other JavaScript object.

For example, let's say we have the following JSON file, which contains information about a user:

{
  "name": "Alice",
  "age": 30,
  "email": "alice@example.com",
  "hobbies": ["reading", "hiking", "cooking"]
}

We can use the fetch() function to read this JSON file and convert it into a JavaScript object, as we learned in the previous section:

fetch('path/to/user.json')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error fetching JSON:', error));

Once we have the JavaScript object, we can access its properties using either dot notation or bracket notation. For example, we can access the user's name like this:

console.log(data.name); // Output: "Alice"

Or like this:

console.log(data['name']); // Output: "Alice"

Similarly, we can access the user's age, email, and hobbies like this:

console.log(data.age); // Output: 30
console.log(data.email); // Output: "alice@example.com"
console.log(data.hobbies); // Output: ["reading", "hiking", "cooking"]

If the JavaScript object contains an array, like the hobbies property in our example, we can use array methods and properties to work with the data. For example, we can loop through the hobbies array and log each item to the console like this:

data.hobbies.forEach(hobby => console.log(hobby));

This would output the following:

reading
hiking
cooking

Conclusion

In this tutorial, we learned how to read JSON files in JavaScript using the fetch() function. We also learned how to convert the JSON data into a JavaScript object and access its properties and values.

By using the techniques we covered in this blog post, you can easily read and work with JSON files in your JavaScript applications, whether you're building a simple website or a complex web application.

Remember that the fetch() function is just one way to read JSON files in JavaScript; there are other methods like using the XMLHttpRequest object, which is an older and more complex way of making network requests. However, the fetch() function is widely supported in modern browsers and is generally the preferred method for reading JSON files in JavaScript.

Now that you know how to read JSON files in JavaScript, you can start using this powerful data interchange format to store and manage data in your applications. Happy coding!