Open In App

How to open JSON file ?

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Create a JSON file, add data in that JSON file.
  • Using JavaScript fetch the created JSON file using the fetch() method.
  • Display the data on the console or in the window.

To create a JSON file:

  • Open the text editor, for example, Visual Studio Code, etc.
  • Create a new file and add the data to it.
  • Save this file with the “.json” extension.

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:

HTML




<!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.

HTML




<!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.



Last Updated : 16 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads