I am looking to allow the user to select a file that will be read and parsed into JSON for storage in their localStorage. However, when reading from the file, each character is interpreted as a key, unlike when directly pasting the JSON string into the function where it is properly parsed.
Can anyone explain why the file method is not working as expected?
Below is the code responsible for reading the file (which results in every character becoming a key within LocalStorage).
<h1>Import/Export</h1>
<button id="export">Export</button>
<br><br>
<input type="file" name="inputfile" id="inputfile">
<br><br>
<!-- <textarea id="input" placeholder="Paste the contents of the exported TXT file here"></textarea> -->
<br>
<br>
<button id="import">Import</button>
<pre id="output" style="display: none;"></pre>
<script type="text/javascript">
document.getElementById('inputfile').addEventListener('change', function() {
var fr=new FileReader();
fr.onload=function(){
document.getElementById('output').textContent=fr.result;
console.log(fr.result)
// Read the JSON
var data = JSON.parse(fr.result);
console.log(data)
Object.keys(data).forEach(function (k) {
localStorage.setItem(k, data[k]);
});
}
fr.readAsText(this.files[0])
})
</script>
And here is the code that works correctly either within a function or when executed in the console:
var data = JSON.parse("JSON STRING GOES HERE");
console.log(data)
Object.keys(data).forEach(function (k) {
localStorage.setItem(k, data[k]);
});