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:
Book[]
from this data?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;
}
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[];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With