Uploading a JSON file and using it

后端 未结 5 2059
深忆病人
深忆病人 2020-12-13 16:00

How can I upload a JSON file on some click on a button on my web page say \"import\", and use it to store in a variable to use and update it using JavaScript.

I have

5条回答
  •  盖世英雄少女心
    2020-12-13 16:30

    Without server side code, your best approach may be to provide a textarea element for the user to copy/paste the JSON into, and then parse it using JSON.parse.

    You could even go as far as to use something like Ace Editor to provide syntax highlighting for JSON - you can see it in action on the Ace Editor Kitchen Sink Demo - select JSON from the dropdown list in the top left.


    Edit:

    Turns out I was wrong. Here is a fiddle demonstrating the FileReader in use, which is exactly what you need:

    https://jsfiddle.net/Ln37kqc0/

    Here is the code:

    Javascript:

    document.getElementById('import').onclick = function() {
        var files = document.getElementById('selectFiles').files;
      console.log(files);
      if (files.length <= 0) {
        return false;
      }
    
      var fr = new FileReader();
    
      fr.onload = function(e) { 
      console.log(e);
        var result = JSON.parse(e.target.result);
        var formatted = JSON.stringify(result, null, 2);
            document.getElementById('result').value = formatted;
      }
    
      fr.readAsText(files.item(0));
    };
    

    HTML:


提交回复
热议问题