14

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?

2 Answers 2

16

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;
}
Sign up to request clarification or add additional context in comments.

Comments

10

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[];

2 Comments

the esModuleInterOp mark as true is required?
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";

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.