Open In App

How to open JSON file ?

In this article, we will open the JSON file using JavaScript.  JSON stands for JavaScript Object Notation. It is basically a format for structuring data. The JSON format is a text-based format to represent the data in form of a JavaScript object.

Approach:



To create a JSON file:

Note: We are using an HTML file to use JavaScript under the script tag.



Example 1: To display the data in the console. First create a JSON file with “.json” extension, here we have named it as load.json with the following code in it.

{
  "users":[
    {
        "site":"GeeksForGeeks",
        "user": "Anurag Singh"
    }
  ]
}

Now, creating an HTML file to use JavaScript code:




<!DOCTYPE html>
<html>
  <body>
    <h1>GeeksForGeeks</h1>
    <button onclick="Func()">Show Details</button>
    <script>
      function Func() {
        fetch("./load.json")
          .then((res) => {
            return res.json();
          })
          .then((data) => console.log(data));
      }
    </script>
  </body>
</html>

Output: In the above snippet of code, we have created a button “Show Details”, when we click on this button the “Func” function is executed. This Func function is basically fetching the details from the “load.json” file. 

The fetch() method return a promise, a promise is actually an object which represents a future result. The then() method is used to wait for the response from the server-side and log it to the console.

Window 

Console

Example 2: To display the data on the window. We are using the same JSON file which is used in Example 1.




<!DOCTYPE html>
<html>
  <body>
    <h1>GeeksForGeeks</h1>
    <button onclick="Func()">Show Details</button>
    <p id="details"></p>
  
  
    <script>
      function Func() {
        fetch("./load.json")
          .then((res) => {
            return res.json();
          })
          .then((data) => document.getElementById("details").innerHTML = 
                (data.users[0].site + " - " + data.users[0].user));
      }
    </script>
  </body>
</html>

Output: In the above code, we have used the same approach as we have used in Example 1, here we have fetched the data from the “load.json” file. We have selected the id “details” then displayed the fetched data in the window using the innerHTML property.


Article Tags :