Home > Back-end >  Read local json into array of type interface
Read local json into array of type interface

Time:10-19

I want to read a local JSON file and put the content to an array of type InputData. The JSON consists of many entries, which also have the format of InputData. I tried to realize my requirements with the following code.

The problem appears at the subscription "TS2339: Property 'subscribe' does not exist on type '{}'."

If I can't subscribe the JSON, how can I read the entries and push them to my array?

    import dataset from "dataset.json";
    
    export interface InputData {
      _id: {
        $oid: String;
      };
      id: String;
      expNumber: Number;
      passed: Boolean;
    }
    
    @Component({
      selector: "app-read-data",
      templateUrl: "./read-data.component.html",
      styleUrls: ["./read-data.component.scss"],
    })
    export class ReadDataComponent implements OnInit {
      
      public data:InputData[];
    
      constructor() {}
    
      ngOnInit(): void {
        this.dataset.subscribe(readData => {
        readData.reduce(t => this.data.push(t));
      });
      console.log("DATA", this.data);
    }

Here is an example for the JSON File:

[{
  "_id": {
    "$oid": "51275"
  },
  "id": "T22F2r",
  "expNumber": 2,
  "passed": false
},{
  "_id": {
    "$oid": "23451"
  },
  "id": "r3322F",
  "expNumber": 2,
  "passed": true
}]

CodePudding user response:

The imported json is treated like a constant object, it is not an observable. It should be enough to assign it.

public data: InputData[] = dataset;

Note: It would be an observable, if you call dataset.json with http from assets.

  • Related