Load JSON File Locally Using Pure JavaScript

Load Json File Locally Using Pure JavaScript
Code Snippet:Read Json File Content from Javascript
Author: Yuval Bar Yosef
Published: May 1, 2024
Last Updated: May 1, 2024
Downloads: 50
License: MIT
Edit Code online: View on CodePen
Read More

This pure JavaScript code allows you to load a JSON file locally. When a file is selected, it reads its content using FileReader.Then, it parses the JSON content and displays it on the webpage. It helps you easily access and display local JSON files.

You can use this code on any webpage to enable users to upload and view JSON files directly. It simplifies the process of loading local JSON data without relying on server-side processing. Moreover, this enhances user experience by providing a straightforward way to interact with JSON files within the browser.

How to Create Load JSON File Locally Using Pure JavaScript

1. Begin by setting up the HTML structure. Create an input element of type ‘file’ with an id of ‘file’ and specify the accepted file type as JSON using the ‘accept’ attribute.

<label for="file"> Upload JSON File: </label>
<input id="file" type="file" accept="application/json">

<p id="fileContent"</p>

2. Next, add some basic styling to improve the visual presentation of the uploaded JSON content.

label, input{
   display: block;
   margin: 20px;
}
#fileContent{
   padding: 10px;
   border: 1px solid #ccc;
   background: #f2f2f2;
   margin: 20px;
  max-width: 460px;
}

3. Now, let’s implement the JavaScript functionality. We’ll create an immediately invoked function expression (IIFE) to encapsulate our code and prevent global scope pollution.

(function(){
    
    function onChange(event) {
        var reader = new FileReader();
        reader.onload = onReaderLoad;
        reader.readAsText(event.target.files[0]);
    }

    function onReaderLoad(event){
        console.log(event.target.result);
      
        var obj = JSON.parse(event.target.result);
      document.getElementById('fileContent').innerHTML = event.target.result;
      
      //alert(event.target.result);
    }
     
    document.getElementById('file').addEventListener('change', onChange);

}());

That’s all! hopefully, you have successfully created the load JSON file locally. If you have any questions or suggestions, feel free to comment below.

Leave a Comment