首页 > 解决方案 > 以角度 6 将 Json 字符串转换为 json 数组

问题描述

嗨,我想将 Json 字符串中的 RestController 响应转换为 json 数组,这是我在控制台中打印的 json 数组字符串。

'{"Impressions":["Budget","CTR","Campaign","Campaign state","Clicks","Conv. rate"],"Clicks":["Budget","CTR","Campaign","Campaign state","Clicks","Conv. rate"],"Revenue":["Budget","CTR","Campaign","Campaign state","Clicks","Conv. rate"]}'

我想将它转换为 json 数组,以便我可以迭代它,

我的要求是迭代数组并将键打印为标签,将值打印为 slect 选项

例子:

印象作为标签,“预算”、“点击率”、“广告系列”、“广告系列状态”、“点击次数”、“转化率”作为选择选项。

这是我的迭代代码

<div>
   <form *ngFor ="let map of mapper">
      <mat-form-field>
         <mat-select placeholder="{{map}}">
            <!--<mat-option>None</mat-option>-->
             <mat-option *ngFor="let option of map"  [value]="option"> 
                {{option}}
             </mat-option>
         </mat-select>
      </mat-form-field>
    </form>
</div>

我的 .ts 课程

this.clientService.getHeaders().subscribe(
      (res) => {
          console.log(res);
          let resSTR = JSON.stringify(res);
          let resJSON = JSON.parse(resSTR);
          this.mapper=Array.of(resJSON._body);
          console.log(this.mapper);
          this.ismapped=false;
      }
);

标签: javascriptjsonangulartypescriptangular6

解决方案


this.clientService.getHeaders().subscribe(
  (res) => {
      console.log(res);
      let result= <any>res;
      this.mapper= result;
      console.log(this.mapper);
      this.ismapped=false;
  }
);

无需进行字符串化然后解析。只需将响应转换为any,然后您就可以将其用作数组。


推荐阅读