Reading JSON file in angular 2 application

Viewed 2412

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.

2 Answers

I tried to apply @Stanislav solution but faced few issues. Eventually the following code worked

Ref: get the value from a FileReader in Angular 2

  • html code

<input (change)=readJson($event);" type="file" />

  • component.ts code

    readJson(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'); } } }

event.target["result"] is the part I modified.

Related