Reputation: 255
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);
}
Upvotes: 4
Views: 8913
Reputation: 1
usually you map response with res => res.json()
somewhere in the service method but json should have a valid format, otherwise it won't parse.
Note, that response is an Object and you can't parse it but only body of the response.
return this.http.get(url,options).map((response) => this.parseResponse(response))
.catch((err) => this.handleError(err));
private handleError(error: any) {
let body = error.json();
return Observable.throw(body);
}
private parseResponse(response: Response) {
return response.json();
}
Upvotes: 0
Reputation: 164129
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)))
Upvotes: 6