Download JSON file and use it

How can I load a JSON file with some click on a button on my web page, I will say "import", and use it to store in a variable that needs to be used and updated using JavaScript.

I read other posts but could not find an answer.

I save the JSON variable using this function:

function save(filename, data){

    if(!data) {
        alert('error : No data')
        return;
    }

    if(typeof data === "object"){
        data = JSON.stringify(data, undefined, 4)
    }

    var blob = new Blob([data], {type: 'text/json'}),
        e    = document.createEvent('MouseEvents'),
        a    = document.createElement('a')

    a.download = filename
    a.href = window.URL.createObjectURL(blob)
    a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':')
    e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
    a.dispatchEvent(e)
 }

This works great, and it loads the file when another export button is clicked. How to load this file back and make a JSON data variable for this file?

+8
source share
3 answers

textarea / JSON- JSON.parse, JSON.parse.

- Ace Editor JSON - Ace Editor Kitchen Sink - JSON .


:

, . , FileReader, , :

https://jsfiddle.net/Ln37kqc0/

:

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:

<input type="file" id="selectFiles" value="Import" /><br />
<button id="import">Import</button>
<textarea id="result"></textarea>
+10

json , .

$("#inputFile").change(function(e) {
    onChange(e);
});

function onChange(event) {
    var reader = new FileReader();
    reader.onload = onReaderLoad;
    reader.readAsText(event.target.files[0]);
}

function onReaderLoad(event){
    //alert(event.target.result);
    var obj = JSON.parse(event.target.result);
    alert(obj);
}
+10

Main download file :

    <input id="uploadEnvironmentFile" type="file" accept="application/json" />


    document.getElementById('uploadEnvironmentFile').onchange = function(evt) {
        try {
            let files = evt.target.files;
            if (!files.length) {
                alert('No file selected!');
        enter code here
                return;
            }
            let file = files[0];
            let reader = new FileReader();
            const self = this;
            reader.onload = (event) => {
                console.log('FILE CONTENT', event.target.result);
            };
            reader.readAsText(file);
        } catch (err) {
            console.error(err);
        }
    }
0
source

All Articles