Saving JSON to and / or loading it from local file

9:20 PM 10/30/2018

This seems to work well on IE.10, Firefox.63 and Chrome.69... but actually, this page only covers loading and saving "the text string" of JSON. JSON as object isn't covered here.

Test


HTML

<div id="test">
	<textarea></textarea>
	<input type="file" accept="application/json">
	<br>
	<button type="button">Load</button>
	<a href="#" download="test.json"></a>
	<button type="button">Save</button>
</div>
			

CSS

#test input[type="file"]{
	width: 1px;
	height: 1px;
	position: absolute;
	z-index: -1;
	overflow: hidden;
}
#test a[download]{
	position: absolute;
	z-index: -1;
}
			

Javascript

var hTest = document.getElementById('test'),
	hText = hTest.getElementsByTagName('textarea')[0], 
	hLoad = hTest.querySelector('input[type="file"]'),
	hSave = hTest.querySelector('a[download]');
	
//install click event handler on load from file button
hLoad.nextElementSibling.addEventListener('click', function(){
	hLoad.click();
}, false);

//install change even handler on load from input
hLoad.addEventListener('change', function(){
	var reader = new FileReader();
	reader.addEventListener('load', function(){
		hText.value = this.result;
	}, false);
	reader.onload = function(){
		hText.value = this.result;
	};
	reader.readAsText(this.files[0]);
}, false);

//install click event handler on save to file button
hSave.nextElementSibling.addEventListener('click', function(){
	var blob = new Blob([hText.value], {type : 'applicatioin/json'});
	if(navigator.msSaveBlob)
		window.navigator.msSaveBlob(blob, hSave.getAttribute('download'));
	else{
		var saveURL = URL.createObjectURL(blob);
		if(hSave.href.search('#') === -1)
			URL.revokeObjectURL(hSave.href);
		hSave.href = saveURL;
		hSave.click();
	}
}, false);
			

Comments