JavaScript Read Local JSON File without jQuery

JavaScript Read Local JSON File without jQuery
Code Snippet:Read Json File Content from Javascript
Author: Yuval Bar Yosef
Published: January 14, 2024
Last Updated: January 22, 2024
Downloads: 794
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code helps you to read local JSON file without jQuery. It allows you to select a local JSON file using an HTML input element. When you choose a JSON file, it reads the file’s content and displays it in an HTML paragraph element. This code is helpful for easily loading and displaying JSON data from a local file without the need for jQuery.

You can modify this code to store the JSON data in a JavaScript variable. Instead of displaying the JSON data in an HTML paragraph element, you can assign it to a variable for further processing. The JSON data will be stored in the jsonData variable, and you can access and manipulate it as needed in your JavaScript code.

How to Read Local JSON File in JavaScript Without jQuery

1. Start by creating the necessary HTML structure. You’ll need an input element to select the JSON file and a paragraph element to display its content.

<input id="file" type="file" />

<p id="fileContent"</p>

2. Now, let’s write the JavaScript code to read and display the JSON file content. The following code should be placed within a <script> tag in your HTML document or in an external JavaScript file.

(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);

}());

You can now utilize the jsonData variable to work with the loaded JSON data in your JavaScript code. For example, you can access specific properties or manipulate the data as needed.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X