【问题标题】:Turn json string into an object array in angular cli在角度cli中将json字符串转换为对象数组
【发布时间】:2017-10-17 08:26:47
【问题描述】:

我想把一个 json 字符串数组变成一个对象数组。 在这种情况下,我有一个从后端接收的字符串

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

我想把这个字符串变成一个英雄数组,然后返回它。

我当前的代码:

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);
   }

有人可以帮忙吗?

更新:

这是解决方案:

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);
   }

【问题讨论】:

    标签: arrays json angular


    【解决方案1】:

    使用map(t=&gt; t.json()):

    return this.http.get(this.heroesUrl)
            .map (t=>t.json())
            .toPromise()
            ...
    

    【讨论】:

    • 好的,这会将它变成一个对象数组,但我需要 Hero[] 返回.map (t=&gt;t.json()) .toPromise() .then(response =&gt; { response as Hero[]; // object array })
    【解决方案2】:

    您的问题是您在解析 JSON 之前尝试循环访问数组:

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

    您应该在访问数组之前解析 JSON 并对其元素进行循环:

    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];
    }
    

    【讨论】:

      【解决方案3】:

      在你的 Hero 类中创建一个构造函数。应该看起来像:

      export class Hero {
        id: number;
        name: string;
      
        constructor(hero?: any) {
          if (hero) {
            this.id = hero.id;
            this.name = hero.name;
          }
        }
      }
      

      现在您需要映射您的数据。我会给你一个我会怎么做的例子:

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

      编辑:

      顺便说一句,我在发布此答案后搜索了您的问题,并立即找到了解决方案 here。您可以在页面上查找 .map 并获取更多示例。

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

      【讨论】:

        【解决方案4】:

        试试这个:

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

        【讨论】:

        • @ninjaxelite 我将发布我的答案检查并尝试这个
        • 遗憾的是,响应未定义,因为另一个组件正在 Hero[] 上调用 slice 方法
        猜你喜欢
        • 1970-01-01
        • 2018-07-20
        • 2019-01-16
        • 2013-08-29
        • 2011-05-21
        • 1970-01-01
        • 2019-07-29
        • 2021-04-02
        • 2012-05-08
        相关资源
        最近更新 更多