TypeScript解析JSON字符串
简单的JSON字符串解析
- 解析如下的JSON字符串数组
let response = '{"id":"1", "name":"Franc"}';
- 定义与待解析的JSON对象一一对应的接口,如{“id”:“1”, “name”:“Franc”}
interface Employee {
id: string
name: string
}
- 通过JSON.parse将字符串转化为JSON对象
let responseObject: Employee = JSON.parse(response);
console.info('===responseObject'+responseObject[0].id)
console.info('===responseObject'+responseObject[1].name)
其他的格式类似
let response = '[{"id":"1", "name":"Franc"}, {"id":"2","name":"Tom"}]';
interface Employee {
id: string
name: string
}
let responseObject: Employee = JSON.parse(response);
console.info('===responseObject'+responseObject[0].id)
console.info('===responseObject'+responseObject[1].name)
存在层层嵌套的JSON字符串解析
- 比如我们需要解析的JSON字符串是如下格式
let jsonObjects = "{
"device_id": "63e48c9a1eaf704179aa270a_fly20230209",
"shadow": [
{
"service_id": "Agriculture",
"desired": {
"properties": null,
"event_time": null
},
"reported": {
"properties": {
"temperature": 23,
"humidity": 30,
"luminance": 434,
"lightStatus": "OFF",
"motorStatus": "OFF"
},
"event_time": "20230216T102043Z"
},
"version": 4111
}
]
}"
- 借助工具,自动生成相应的接口
比如:在线JSON转typescript工具:
生成的接口如下:
export interface Desired {
properties?: any;
event_time?: any;
}
export interface Property {
temperature: number;
humidity: number;
luminance: number;
lightStatus: string;
motorStatus: string;
}
export interface Reported {
properties: Property;
event_time: string;
}
export interface Shadow {
service_id: string;
desired: Desired;
reported: Reported;
version: number;
}
export interface RootObject {
device_id: string;
shadow: Shadow[];
}
- 定义一个根接口类型的变量,然后将需要解析的变量通过“JSON.parse()”将字符串转化为JSON对象即可
let jsonObject: RootObject = JSON.parse(data.result);
但是有时候,我们从网络上请求回来的数据时本身就是JSON格式时,如果通过直接赋值无法解决可以尝试如下方法
let jsonObject: RootObject = JSON.parse(data.result as string); //或者可以试一试 let jsonObject: RootObject = JSON.parse(JSON.stringify(data.result));