For a school project I got, I need to display the JSON file content that is uploaded using input in html. It contains appointments for mechanics, but I can't seem to figure out how to get the content out of the uploaded file and into an variable to store it and to display it in a span for now.
this is the code I have currently:
js
function importFile() {
var importedFile = document.getElementById('import-file').files[0];
var fileContent = JSON.parse(importedFile.value);
document.getElementById('json-file').innerHTML = fileContent;
}
html
<label for="import-file">Upload the testfile:</label>
<input type="file" name="import-file" id="import-file" accept="application/json" required>
<button onclick="importFile()">Submit</button>
<p>
<span id="json-file"></span>
</p>
JSON file
[
{
"Appointment": {
"Id": 2,
"nameCustomer": "gibberish",
"addressCustomer": "gibberish 34, gibberish",
"timeOfAppointment": "2020-01-07T10:00:00Z",
"nearbyTramStop": "gibberish",
"distanceToStop": 340,
"reasonAppointment": "gibberish",
"nameMechanic": "gibberish"
}
},
{
"Appointment": {
"Id": 1,
"naamKlant": "gibberish",
"adresKlant": "gibberish 12, gibberish",
"gewenstTijdstip": "2020-01-07T12:15:00Z",
"dichtsbijzijndeHalte": "gibberish",
"afstandHalte": 200,
"redenAfspraak": "gibberish",
"naamMonteur": "gibberish"
}
}
]
For now I just want to be able to display the content as text in the paragraph. As you can see I tried parsing it, but no succes. I can't seem to find anything online that could help me unfortunately.
These are things I tried:
var fileContent = JSON.parse(importedFile);
var fileContent = importedFile.value;
When I use parse, I get this error:
VM4077:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at importFile (main.js:129)
at HTMLButtonElement.onclick (index.html?import-file=BBMonteurs.json:30)
Does anyone know a solution for my problem? Thanks in advance!