Typescript :转换/解析字符串文本为JSON对象的教程

如何在typescript中转换/解析字符串文本为JSON对象

在typescript/javascript中,从REST API或后端服务器返回的响应是String JSON文本的形式,开发者需要知道转换为JSON或类对象的方法。

Typescript是javascript的一个超集,具有类型断言的功能。在javascript中,我们使用JSON.parse()方法来转换为JSON,你可以查看 这里

在这篇博文中,你将通过下面的例子学习如何将字符串文本解析为TypeScript接口或对象。

  • JSON.parse()方法
  • 将JSON字符串文本转换为Typescript类或接口对象
  • 将字符串转为数组类对象的例子
  • 给出一个String格式的JSON文本--用单引号括起来。

    let employee = '{"name": "Franc","department":"sales","salary":5000}';  
    

    解析JSON字符串文本

    JSON.parse()方法用来解析给定的JSON文本字符串并转换为JSON对象,这是普通的javascript,在typescript中工作

    const employee = '{"name": "Franc","department":"sales"}';  
    console.log(typeof employee)  
    let jsonObject = JSON.parse(employee);  
    console.log(typeof jsonObject) //object  
    console.log(jsonObject) //{ name: 'Franc', department: 'sales' }  
    console.log(jsonObject.name)  // Franc  
    console.log(jsonObject.department) // sales  
    string  
    object  
    { name: 'Franc', department: 'sales' }  
    Franc  
    sales  
    

    返回的对象是一个普通的对象,它可以保存任何数据,这种方法唯一的问题是没有使用typescript提供的类型功能,而不是一个普通的对象,如果你转移到Typescript自定义对象,你有很多优势,静态类型在编译的时候可以得到验证错误。
    让我们看一个例子,在 typescript 中转换 String JSON 类对象。

    转换/解析String到Typescript类对象

    给定字符串文本。

    const employee = '{"name": "Franc","department":"sales","salary":5000}';

    编写一个具有JSON对象的所有字段的类或接口,其类型如下所示

    interface Employee { name: string; department: string; salary: number;

    下面是转换为对象类的示例代码,声明的对象为Employee类型,它持有解析的JSON对象

    var jsonObject: Employee = JSON.parse(emloyee); console.log(typeof jsonObject) //object console.log(jsonObject) //{ name: 'Franc', department: 'sales' } console.log(jsonObject.name) // Franc console.log(jsonObject.department) // sales string object{ name: 'Franc', department: 'sales', salary: 5000 } Franc sales

    例子--将JSON字符串转换为对象/接口的数组

    有些时候,响应包含一个对象数组,创建Employee接口,并将返回的数据输入到类的数组中。 将JSON.parse()返回的数据投到Employee数组中。

    let response='[{"id":"1", "name":"Franc"}, {"id":"2","name":"Tom"}]'; export interface Employee { id: string name: string let responseObject:Employee[]= JSON.parse(response);