[英]Parse JSON array in Typescript
i have a JSON response from remote server in this way: 我以这种方式从远程服务器获得JSON响应:
{
"string": [
{
"id": 223,
"name": "String",
"sug": "string",
"description": "string",
"jId": 530,
"pcs": [{
"id": 24723,
"name": "String",
"sug": "string"
}]
}, {
"id": 247944,
"name": "String",
"sug": "string",
"description": "string",
"jlId": 531,
"pcs": [{
"id": 24744,
"name": "String",
"sug": "string"
}]
}
]
}
In order to parse the response, to list out the "name" & "description", i have written this code out: 为了解析响应,列出“名称”和“描述”,我已经写出了这个代码:
interface MyObj {
name: string
desc: string
}
let obj: MyObj = JSON.parse(data.toString());
My question is how do i obtain the name and description into a list that can be displayed. 我的问题是如何在可以显示的列表中获取名称和描述。
You gave incorrect type to your parsed data. 您为解析的数据提供了错误的类型。 Should be something like this:
应该是这样的:
interface MyObj {
name: string
description: string
}
let obj: { string: MyObj[] } = JSON.parse(data.toString());
So it's not MyObj
, it's object with property string
containing array of MyObj
. 所以它不是
MyObj
,它的对象是包含MyObj
数组的属性string
。 Than you can access this data like this: 你可以像这样访问这些数据:
console.log(obj.string[0].name, obj.string[0].description);
Instead of using anonymous type, you can also define interface
for it: 您也可以为其定义
interface
,而不是使用匿名类型:
interface MyRootObj {
string: MyObj[];
}
let obj: MyRootObj = JSON.parse(data.toString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.