Angular で JSON をパースする
    
    Rana Hasnain Khan
    2022年5月31日
    
    Angular
    Angular JSON
    
 
この記事では、Angular で JSON を解析する方法を例を挙げて説明します。
Angular で JSON をパースする
Angular アプリケーションで API を使用する場合、JSON での応答に遭遇します。API から JSON 形式でデータを取得している可能性があり、それをテーブルに表示する必要がある場合があります。
このために、JSON データを解析する必要があります。例を挙げて、JSON の stringify メソッドを使用して JSON データを作成してみましょう。
このメソッドは、あらゆるものを JSON 形式に変換するために使用されます。次に、その JSON を使用して、JSON parse() の別のメソッドを使用して解析できます。
parse() メソッドは問題なく JSON を解析できます。
サンプルコード:
# Angular
import { Component, VERSION, OnInit } from '@angular/core';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  strInfo: any;
  parseInfo: any;
  myInfo =
    {
      "id": 0,
      "guid": "9b06a996-23f4-46ff-a007-a6bca1f9c1f3",
      "balance": "$1,590.37",
      "age": 33,
      "name": "Chaney Harrell",
      "gender": "male",
      "company": "GOGOL",
      "email": "chaneyharrell@gogol.com",
      "phone": "+1 (836) 566-3872",
      "address": "716 Grafton Street, Rodanthe, West Virginia, 6757"
    }
  ngOnInit() {
    console.log(this.myInfo);
    this.strInfo = JSON.stringify(this.myInfo);
    console.log('After using Stringify :', this.strInfo);
    this.parseInfo = JSON.parse(this.strInfo);
    console.log('After Parsing Json Info:', this.parseInfo);
  }
}
出力:

stringify() を使用すると、データを完全な JSON に変換できます。次に、JSON データを問題なく解析できる JSONparse() の別の関数を使用できます。
        チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe
    
Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.
LinkedIn