Skip to content

Instantly share code, notes, and snippets.

@mwrouse
Last active March 1, 2023 14:19
Show Gist options
  • Save mwrouse/f061f6f56cbc8b0576367bddee523a79 to your computer and use it in GitHub Desktop.
Save mwrouse/f061f6f56cbc8b0576367bddee523a79 to your computer and use it in GitHub Desktop.
Reading JSON File Input
window.addEventListener('load', function() {
var upload = document.getElementById('fileInput');
// Make sure the DOM element exists
if (upload)
{
upload.addEventListener('change', function() {
// Make sure a file was selected
if (upload.files.length > 0)
{
var reader = new FileReader(); // File reader to read the file
// This event listener will happen when the reader has read the file
reader.addEventListener('load', function() {
var result = JSON.parse(reader.result); // Parse the result into an object
console.log(result);
console.log(result.name);
console.log(result.age);
console.log(result.occupation);
});
reader.readAsText(upload.files[0]); // Read the uploaded file
}
});
}
});
<!DOCTYPE html>
<html>
<head>
<title>File Input</title>
</head>
<body>
<input type="file" id="fileInput">
<script src="index.js"></script>
</body>
</html>
{
"name": "Michael Rouse",
"age": "20",
"occupation": "Student"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment