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.
Similar Code Snippets:
I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.