I have a file location.json
, containing JSON string of the form:
{
"locations": [
{
"id": 1,
"places": [
{
"id": 1,
"city": "A",
"state": "AB"
}
]
}
}
I created classes of the form:
export class Location{
constructor(public id: number,
public places: Place[],
}
export class Place {
constructor(
public id: number,
public city: string,
public state: string
}
How do I parse the JSON string to object? I did something like this:
...
export class DashboardComponent {
locations: Locations[];
constructor(private locationService:LocationService) {
this.getLocations()
}
getLocations(){
this.locationService.get('assets/location.json')
.subscribe(res => this.location = res);
}
Depending on what's the result for the subsriber it can be:
.map(res => this.location = res.json().locations);
Or:
.subscribe(res => this.location = JSON.parse(res).locations);
But keep in mind that that won't instiantiate instances for your classes, it will only assign the values as regular js object which match the following:
interface Location {
id: number;
places: Place[];
}
interface Place {
id: number;
city: string;
state: string;
}
If you want instances of the classes you'll need to do something like:
JSON.parse(res)
.locations.map(location => new Location(location.id,
location.places.map(place => new Place(place.id, place.city, place.state)))
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