I recently have been working on loading a local JSON file parsing it and displaying it using Javascript and I think I got it to where I really like it. I would like to know if anyone knows if there is a "purer" way of doing this using just Javascript without libraries.
<!DOCTYPE html>
<meta charset="UTF-8" />
<input type="file" id="files" name="files" accept=".json"/>
<output id="list"></output>
<div id="traveler_num"></div>
<div id="first_name"></div>
<script>
//stores the output of a parsed JSON file
const parsed = jsonText => JSON.parse(jsonText);
//creates a new file reader object
const fr = new FileReader();
function writeInfo (data) {
//modifies the DOM by writing info into different elements
document.getElementById('traveler_num').innerHTML = 'Traveler: ' + data.traveler_num;
document.getElementById('first_name').innerHTML = 'First Name: ' + data.first_name;
};
function handleFileSelect (evt) {
//function is called when input file is Selected
//calls FileReader object with file
fr.readAsText(evt.target.files[0])
};
fr.onload = e => {
//fuction runs when file is fully loaded
//parses file then makes a call to writeInfo to display info on page
writeInfo(parsed(e.target.result));
};
//event listener for file input
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>