Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
7
rated 0 times [  9] [ 2]  / answers: 1 / hits: 47782  / 8 Years ago, mon, march 21, 2016, 12:00: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 gone through the other posts but could not find any answer.



I am saving 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 is working fine and it downloads the file on clicking another button say export.
How upload this file back and make a JSON variable of this file data?


More From » javascript

 Answers
6

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:



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

[#62864] Friday, March 18, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tomas

Total Points: 165
Total Questions: 111
Total Answers: 103

Location: Maldives
Member since Tue, Dec 21, 2021
2 Years ago
tomas questions
Thu, Jan 27, 22, 00:00, 2 Years ago
Mon, May 10, 21, 00:00, 3 Years ago
Tue, Jan 5, 21, 00:00, 3 Years ago
;