How to read JSON from HTML file input

← PrevNext →

You can extract and read JSON from an external file using the URL or you can select a JSON file using HTML file input. I'll show you how to read JSON file using the file input.

I have an file input element on my web-page that only allows to select JSON files.

🚀 I have used this method recently in one my projects and it works fine. Check this out.

<body>
    <input type="file" id="file" accept="application/json" onchange="get_json_data(this.files)" />
</body>
<script>
    let get_json_data = (files) => {
        if (files.length > 0) {
            const file = files[0];
            let reader = new FileReader();
            reader.onload = function (e) {
                console.log(e.target.result);       // Output: The JSON data.
            };
            reader.readAsText(file);
        }
    }
</script>
Try it

In the above script, I am using the FileReader API to read the JSON file. Learn more about FileReader API.

← PreviousNext →