Skip to content

JavaScript read local JSON file

  • by

In JavaScript, you can use the XMLHttpRequest object or the newer fetch API to read a local JSON file. Here’s an example of how you can accomplish this using the fetch API:

fetch('path/to/file.json')
  .then(response => response.json())
  .then(data => {
    // `data` variable contains the JSON data from the file
    console.log(data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

Or use the XMLHttpRequest object. Here’s an example:

var request = new XMLHttpRequest();
request.open("GET", "path/to/file.json", true);
request.onreadystatechange = function () {
  if (request.readyState === 4 && request.status === 200) {
    var data = JSON.parse(request.responseText);
    // `data` variable contains the JSON data from the file
    console.log(data);
  }
};
request.send();

JavaScript read local JSON file example

Simple example code.

<!DOCTYPE html>
<html>
<head>
  <title>Read Local JSON File</title>
</head>
<body>
  <button onclick="readJSON()">Read JSON</button>

  <script>
    function readJSON() {
      var request = new XMLHttpRequest();
      request.open("GET", "path/to/file.json", true);
      request.onreadystatechange = function () {
        if (request.readyState === 4 && request.status === 200) {
          var data = JSON.parse(request.responseText);
          // `data` variable contains the JSON data from the file
          console.log(data);
        }
      };
      request.send();
    }
  </script>
</body>
</html>

Output:

JavaScript read local JSON file

In this example, the JSON data is logged to the console. However, you can perform any necessary operations with the data variable, such as displaying it on the webpage or manipulating the data in any way you need.

Remember to replace "path/to/file.json" with the actual relative or absolute path to your JSON file.

Do comment if you have any doubts or suggestions on this Js Json topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *