This tutorial will guide you through the process of creating a solution using JavaScript to read local JSON files without relying on the jQuery library. This is particularly useful for scenarios where you want to avoid external dependencies, keep your code lightweight, or simply prefer using vanilla Javascript for file handling.
HTML Structure
First, you need to create the basic HTML elements to allow file selection and display the content of the JSON file.
Step 1: File Input and Display Area
Add an input element with the type “file” to enable users to select a local JSON file. Also, include a paragraph element where the file content will be displayed.
<input id="file" type="file" />
<p id="fileContent"</p>
<script src="./script.js"></script>
JavaScript Functionality
Next, you’ll implement the JavaScript code to handle file selection, read the file content, and display it on the page.
Step 2: Implementing the File Reading Logic
Create a Javascript function to read the local JSON file and display its content into paragraph tag.
(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 it! You’ve successfully created a mechanism to read local JSON files using Javascript without jQuery. This approach provides a simple and efficient way to handle JSON data from local files directly in the browser.







