Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript, Angular 2 - Parse Json to object in http

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);
  }
like image 691
kenadet Avatar asked May 16 '17 16:05

kenadet


1 Answers

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)))
like image 178
Nitzan Tomer Avatar answered Nov 09 '22 00:11

Nitzan Tomer