【问题标题】:How to read uploaded JSON file [duplicate]如何读取上传的 JSON 文件 [重复]
【发布时间】:2020-02-03 20:09:11
【问题描述】:

对于我得到的一个学校项目,我需要显示使用 html 中的输入上传的 JSON 文件内容。它包含机械师的约会,但我似乎无法弄清楚如何将内容从上传的文件中取出并放入一个变量中以存储它并在跨度中显示它。

这是我目前拥有的代码:
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 文件

[
  {
    "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"
    }
  }
]

现在我只想将内容显示为段落中的文本。如您所见,我尝试解析它,但没有成功。不幸的是,我似乎无法在网上找到任何可以帮助我的东西。

这些是我尝试过的:

var fileContent = JSON.parse(importedFile);
var fileContent = importedFile.value;

当我使用解析时,我得到这个错误:

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)

有人知道我的问题的解决方案吗?提前致谢!

【问题讨论】:

  • importedAppointments 来自哪里?你的意思是JSON.parse(importedFile.value)?
  • 这个错误说明你可能有PHP错误或者JSON格式不正确!而且你也必须修复你的脚本:var fileContent = JSON.parse(importedAppointments); var fileContent = fileContent.value;

标签: javascript json


【解决方案1】:
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); 
}

【讨论】:

    猜你喜欢
    • 2019-02-14
    • 2019-12-11
    • 2012-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多