I have a file data.json which I want to import in my angular 2 application. I am getting file with HTML input tag.
<input type="file" (change)="onImport($event)"/>
in my typescript file I want to read this data.json file and store the content of file in JSON array. I have searched but couldn't find any way to read file or any library which could help me with this.
Use FileReader
from the File API and JSON.parse()
method like:
onImport(event) {
var file = event.srcElement.files[0];
if (file) {
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (evt) {
console.log(JSON.parse(evt.target.result));
}
reader.onerror = function (evt) {
console.log('error reading file');
}
}
}