How to access data of uploaded JSON file?
Here's a shorthand version of Sam Greenhalghs answer that works for me.
$(document).on('change', '.file-upload-button', function(event) {
var reader = new FileReader();
reader.onload = function(event) {
var jsonObj = JSON.parse(event.target.result);
alert(jsonObj.name);
}
reader.readAsText(event.target.files[0]);
});
<input class='file-upload-button' type="file" />
You will need an HTML5 browser, but this is possible.
(function(){
function onChange(event) {
var reader = new FileReader();
reader.onload = onReaderLoad;
reader.readAsText(event.target.files[0]);
}
function onReaderLoad(event){
console.log(event.target.result);
var obj = JSON.parse(event.target.result);
alert_data(obj.name, obj.family);
}
function alert_data(name, family){
alert('Name : ' + name + ', Family : ' + family);
}
document.getElementById('file').addEventListener('change', onChange);
}());
<input id="file" type="file" />
<p>Select a file with the following format.</p>
<pre>
{
"name": "testName",
"family": "testFamily"
}
</pre>
Since all answers seem unnecessarily complex, here's a simple async function that returns the file contents as an Object:
async function parseJsonFile(file) {
return new Promise((resolve, reject) => {
const fileReader = new FileReader()
fileReader.onload = event => resolve(JSON.parse(event.target.result))
fileReader.onerror = error => reject(error)
fileReader.readAsText(file)
})
}
const object = await parseJsonFile(file)