如何在angular中把json转换为对象/从对象转换为JSON?

648 阅读2分钟

Angular是前端的MVC框架,它通过JSON格式与服务器进行通信。

在某些情况下,你需要将JSON对象从Angular应用程序发送到/消耗到REST API。Angular使用typecript对象,这是javascript的超集,它总是需要将对象转换为/从JSON。

这项工作将涵盖不同的方法来转换JSON到对象或angular中的对象到json。

这也是Angular/typescript工作中的一个热门面试问题。

在应用程序中,REST API被Angular应用程序使用HTTP库消费,数据以JSON的格式出现,你如何将JSON转换为对象?

我们有很多方法可以将JSON解析为/从一个javascript对象。

JSON是javascript语言中内置的一个对象。

在JSON对象中,有两种方法

  • JSON.stringify() 方法 对象的字符串版本,它是一个对象到JSON字符串的转换。
  • JSON.parse() - 解析JSON对象的字符串并创建javascript对象
import { Component, OnInit } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  name = "Angular";
  stringJson: any;
  stringObject: any;
  courseList = [
    {
      courseid: "1",
      coursename: "Java programming",
      author: "Franc"
    },
    {
      courseid: "2",
      coursename: "Learn Typescript programming",
      author: "John"
    }
  ];

  ngOnInit() {
    // Convert String obect to JSON
    this.stringJson = JSON.stringify(this.courseList);
    console.log("String json object :", this.stringJson);
    console.log("Type :", typeof this.stringJson);

    // ConvertjSON to an object
    this.stringObject = JSON.parse(this.stringJson);
    console.log("JSON object -", this.stringObject);
  }
}

下面是在浏览器中显示输出的html代码


<p>
Convert jsOn to/from Object Example</p>

<table>
      <tr *ngFor="let item of stringObject">
        <td>{{item.courseid}}</td>
        <td>{{item.coursename}}</td>
        <td>{{item.author}}</td>
      </tr>

</table>

你在浏览器和控制台中看到的输出

Angular javascript json to object example

在angular中解析/映射JSON对象为Typescript对象

创建一个宣布JSON对象的所有字段的类型脚本接口。

为上述JSON对象创建了课程接口。

export interface Course {
    couseid: string;
    coursename: string;
    author: string;
}

接下来,使用JSON.parse()方法解析JSON课程对象,返回任意类型的通用对象。将这个通用对象转换为课程类型的对象。

这在javascript中是行不通的。因为我们正在使用typescript中的类型功能将泛型转换为接口。

这种方法的好处是可以避免运行时的错误,因为大部分的类型检查只发生在编译时。

let jsonObject: any = JSON.parse(course);
let course: Course = jsonObj;

使用json pInputText将Javascript对象解析为json

在angular组件中,如果你想把javascript对象显示为JSON的更漂亮的打印格式。JSON管道被使用。

JSON pipe 是一个angular内置的管道

在组件的HTML模板中,提供以下一行代码

{{stringObject | json }}

显示的输出是以JSON格式在浏览器中打印的。

这有助于开发人员在调试过程中打印JSON对象,以解决任何问题。