0

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!

Triable
  • 53
  • 2
  • 10
  • Where does `importedAppointments` come from? Do you mean `JSON.parse(importedFile.value)`? – m02ph3u5 Feb 03 '20 at 20:11
  • This error shows that you probably have a PHP error or the JSON format is not correct! And also you have to fixe your script too : `var fileContent = JSON.parse(importedAppointments); var fileContent = fileContent.value;` – Adnane Ar Feb 03 '20 at 20:14

1 Answers1

2
function importFile() {
    var importedFile = document.getElementById('import-file').files[0];

    var reader = new FileReader();
    reader.onload = function() {
      var fileContent = JSON.parse(reader.result);

      // Do something with fileContent
      // document.getElementById('json-file').innerHTML = fileContent;  
    };
    reader.readAsText(importedFile); 
}

Paul
  • 1,002
  • 4
  • 6