1

In my current Angular 8 project I have two JSON files which should be connected to one JSON array. The new file should then be exported.

After googling for a long time I didn't find a solution how to use the two JSON files, which I call up via two HTML inputs, so that I can combine both files in the Angular Component to form a JSON array with input from both JSON files.

My current code:

JsonConverterComponent.html

<div class="form-group">
   <label for="Json1">Json 1</label>
      <input [(ngModel)]="json1" type="file" id="Json1" required>
</div>
<div class="form-group">
   <label for="Json2">Json 2</label>
      <input [(ngModel)]="json2" type="file" id="Json2" required>
</div>
<button [buttonLabel]="buttonNameJson" [disableCheck]="!json1 || !json2" (click)="combineJSON()"></button>

JsonConverterComponent.TS

export class JsonConverterComponent implements OnInit {

  constructor(private http: HttpClient) { }

  ngOnInit() {
  }

  buttonNameJson = "Combine JSON";
  json1: File;
  json2: File;
  test: File;

  one = this.json1;
  two = this.json2;

  public combineJSON() {
    this.test = this.one;
    console.log(this.test);
  }
}

If I just want to call up the content of one of the two imported JSON files, I always get the error "undefined".

What do I have to do so that I can use the individual JSON in JsonConverterComponent.ts?

1 Answer 1

3

The ngModel directive can't be used on a input of type file, you have to react on the change event like this:

<input (change)="onFileChange($event)" type="file" id="Json1" required>

<input (change)="onFileChange($event)" type="file" id="Json2" required>

Then in the TypeScript file:

onFileChange(event){
    const fileToLoad = event.target.files[0];
    const fileReader = new FileReader();
    fileReader.onload = function(fileLoadedEvent){
        const textFromFileLoaded = fileLoadedEvent.target.result;
        const json = JSON.parse(textFromFileLoaded);
        console.log(json);
    };
    fileReader.readAsText(fileToLoad, "UTF-8");
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, that works fine so far, but when I try to connect the two JSON files I only get one fakepath. C: \ fakepath \ JsonOne.jsonC: \ fakepath \ JsonTwo.json
What do you mean by "connect the two JSON files?"
I want to convert the content of both JSON files into one file
onload event will be fired after the content is read so your logic to convert the two JSON files should be inside the onLoad function.
how extract the const json in some component property?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.