JSON array from local file to Typescript array in Angular 5

12,172

Solution 1

You could load the file with import:

import data from 'path/to/data.json';

And assign that to an array of type Book[]:

@Component({...})
class Foo {
   books: Book[] = data;
}

demo

Also add a wildcard module definition in src/typings.d.ts to tell the TypeScript compiler how to import *.json:

declare module "*.json" {
  const value: any;
  export default value;
}

Solution 2

This answer could help someone, although it pertains to Typescript 4.(Angular 5 supports Typescript 2 ).

The sample JSON file content (data.json):

[
  {
    "Gender": "Male",
    "HeightCm": 171,
    "WeightKg": 96
  },
  {
    "Gender": "Male",
    "HeightCm": 161,
    "WeightKg": 85
  }
]

Appropriate tsconfig.json entry:

{
    "compilerOptions": {  
      "esModuleInterop": true
      "resolveJsonModule": true
    } 
}

The code that reads the JSON content into an interface Person:

import data from './data.json';

interface Person{
    Gender: string,
    HeightCm: number,
    WeightKg: number
}

const personArray:Person[] = data as Person[];
Share:
12,172
Nikita Marinosyan
Author by

Nikita Marinosyan

Updated on June 22, 2022

Comments

  • Nikita Marinosyan
    Nikita Marinosyan almost 2 years

    I am using Angular 5 to develop a web app. I have JSON file which looks like this:

    [
      {
            "id": 0,
            "title": "Some title"
      },
      {
            "id": 1,
            "title": "Some title"
      },
      ...
    ]
    

    This file is stored locally. I also have an interface:

    export interface Book {
      id: number;
      title: string;
    }
    

    The questions are how do I:

    1. Fetch the data from the file?
    2. Create an array of type Book[] from this data?
  • Quethzel Díaz
    Quethzel Díaz almost 3 years
    the esModuleInterOp mark as true is required?
  • Prem G
    Prem G over 2 years
    answer is correct, but "esModuleInterop": true config gave me errors in import example : import * as moment from "moment"; to resolve errors, changed to import moment from "moment";