All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Reading Local JSON File In JavaScript

Last Updated : Aug 19, 2023

Reading Local JSON File In JavaScript

In this article we will show you the solution of reading local JSON file in JavaScript, JavaScript offers a variety of methods for reading local JSON files. Using the FileReader object as well as the File API is one frequent technique.

You must first add a "file"-type input element to your HTML markup and give it an ID. The getElementById method in JavaScript is then used to retrieve this detail.

The "change" event, that is caused while a record is selected, is then connected as an event listener to the input element.

You can build a FileReader item and use the files belongings to retrieve the favored record inside the occasion handler code.

You can study a record's contents using the FileReader object. Using the end result property of the FileReader object, you could get the JSON records after the document has been successfully read.

The JSON.Parse() approach can then be used to convert the JSON information right into a JavaScript object.

Finally, you can modify and use the JSON statistics as vital in your JavaScript code.

Now move to the concept of reading local json file in javascript.

Step By Step Guide On Reading Local JSON File In JavaScript :-

<!DOCTYPE html>
<html>
  <head>
    <title>Read Local JSON File</title>
  </head>
  <body>
    <input type="file" id="jsonFileInput" />
    <pre id="jsonContent"></pre>
    <script>
      // Function to handle file selection
      function handleFileSelect(event) {
        const file = event.target.files[0];
        // Create a FileReader object
        const reader = new FileReader();
        // Event listener for file load
        reader.onload = function (e) {
          const jsonContent = e.target.result;
          const jsonData = JSON.parse(jsonContent);
          // Access and display the JSON data
          document.getElementById("jsonContent").textContent = JSON.stringify(
            jsonData,
            null,
            2
          );
        };
        // Read the file as text
        reader.readAsText(file);
      }
      // Attach event listener to file input element
      const fileInput = document.getElementById("jsonFileInput");
      fileInput.addEventListener("change", handleFileSelect, false);
    </script>
  </body>
</html>
  1. We have an HTML page with a pre element for showing the JSON text and a file input element.
  2. The handleFileSelect function is called when a file is chosen via the file input. It uses event.target.files[0] to fetch the desired file and takes the event object as an argument.
  3. We create a FileReader object called reader in order to read the file's content.
  4. This object enables asynchronous reading of the file's contents.
  5. The reader's onload event is then connected to an event listener.
  6. When the file is loaded successfully, this event is triggered.
  7. We get the JSON content from the file's content, e.target.result, inside the event handler function.
  8. We use JSON.Parse() to convert the jsonContent into a JavaScript object in order that we are able to get access to and display the JSON facts.
  9. This transforms the JSON string right into a possible, based object.
  10. Finally, we regulate the text content within the pre-element with the JSON data the use of document.GetElementById("jsonContent").TextContent.
  11. JSON.Stringify(jsonData, null, 2) is used to prepare the JSON data with indentation for simpler reading.
  12. Using addEventListener(), we finish the setup through including an event listener to the document input element.
  13. This makes sure that each time a file is selected, the handleFileSelect function is called.

Conclusion :-

As a result, we have successfully learned the JavaScript idea of reading local JSON files.

We also discovered that this activity is frequently carried out using the FileReader object or the File API.

This makes it possible for you to access and work with JSON data inside JavaScript, which opens up a range of data processing and utilization possibilities.

I hope this article on reading local JSON file in JavaScript helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Anjali

Experienced Computer Programmer with a broad range of experience in technology. Strengths in application development and Object Oriented architecture design, front end programming, usability and multimedia technology. Expert in coding languages such as C, C++ Java, JavaScript, PHP and more.

Follow Anjali On Linkedin 🡪