2

I would like to turn a json string array into an object array. In this case I have a string receiving from backend

[{"id_pk":3,"heroname":"myherooo"},{"id_pk":12,"heroname":"Narco"}]

and I would like to turn this string into a Hero array and then return it.

My current code:

getHeroes(): Promise<Hero[]> {
     return this.http.get(this.heroesUrl)
                .toPromise()
                .then(response => {
                  console.log(response);
                  let heroes: Hero[];
                  let jo = response.text(); // [{"id_pk":3,"heroname":"myherooo"},{"id_pk":12,"heroname":"Narco"}]
                  console.log("jo: "+jo);
                  for(let i=0;i<jo.length;i++){
                      console.log("ele:  "+JSON.parse(response.text()[i])); // SyntaxError: Unexpected end of JSON input
                      heroes[i] = JSON.parse(response.text()[i]);
                  }
                  heroes;

                })
                .catch(this.handleError);
   }

Can anybody help?

Update:

This is the solution:

getHeroes(): Promise<Hero[]> {
     return this.http.get(this.heroesUrl)
                .map (t=>t.json())
                .toPromise()
                .then(response => response.map(i => new Hero(i.id_pk, i.heroname)))
                .catch(this.handleError);
   }

4 Answers 4

2

Use map(t=> t.json()):

return this.http.get(this.heroesUrl)
        .map (t=>t.json())
        .toPromise()
        ...
Sign up to request clarification or add additional context in comments.

1 Comment

ok this this turns it into an object array but I need Hero[] to return .map (t=>t.json()) .toPromise() .then(response => { response as Hero[]; // object array })
1

Your problem is that you were trying to loop and access the array before parsing the JSON in :

heroes[i] = JSON.parse(response.text()[i]);
//And then in
heroes[i] = JSON.parse(response.text()[i]);

You should parse the JSON before accessing the array an looping over its elements:

let jo = JSON.parse(response.text()); 
console.log("jo: "+jo);
for(let i=0;i<jo.length;i++){
     console.log("ele:  "+jo[i]); 
     heroes[i] = jo[i];
}

Comments

1

Create a constructor in your Hero class. Should look something like:

export class Hero {
  id: number;
  name: string;

  constructor(hero?: any) {
    if (hero) {
      this.id = hero.id;
      this.name = hero.name;
    }
  }
}

now you need to map your data. I'll give you an example of how i would do it:

this.heroService.getHeroes().subscribe(
  response => this.heroes = response.map(h => new Hero(h)),
  error => console.log(error)
);

Edit:

By the way, i googled your question after i posted this answer and i immediately found a solution here. You can look for .map on the page and get more examples.

this.results = res.json().results.map(item => { 
  return new SearchItem(
      item.trackName,
      item.artistName,
      item.trackViewUrl,
      item.artworkUrl30,
      item.artistId
  );
});

Comments

0

Try this :

getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
        .toPromise()
        .then(res => <Hero[]>res.json());
}

2 Comments

@ninjaxelite i will post my answer check and try this
sadly the response is undefined cause another component is calling slice method on Hero[]

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.