TypeScript - 如何将 JSON 数组解析为自定义对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47047907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript - how to parse JSON array into array of custom objects
提问by CustardBun
I'm relatively new to this space, so apologies if I'm using some of the wrong terminology. Feel free to ask for clarification.
我对这个领域比较陌生,所以如果我使用了一些错误的术语,我深表歉意。随时要求澄清。
I have some typescript interfaces:
我有一些打字稿接口:
export interface Item {
id: string
type: string
state: string
}
export interface ItemResponse {
someData1: string
someData2: string
itemListResponse: Array<Item> // in reality just a JSON string containing serialized Items in an Array
}
The ItemResponse is populated when calling an external service (somewhat) correctly:
ItemResponse 在正确调用外部服务(有点)时被填充:
The result is an of ItemResponses. For now, say the size of the ItemResponse array is 1, but that there are multiple Items in the itemListResponse array.
结果是 ItemResponses。现在,假设 ItemResponse 数组的大小为 1,但 itemListResponse 数组中有多个 Item。
The itemListResponse is actually just a json string:
itemListResponse 实际上只是一个 json 字符串:
"[{"id":"blah", "type":"blah", ...}, {"id":"blah2",.... },...]"
How would I convert this into an Array of Item?
我如何将它转换为一个项目数组?
I think I'm familiar with parsing from JSON to a single object, but not how to do this with an array.
我想我熟悉从 JSON 解析为单个对象,但不熟悉如何使用数组来执行此操作。
回答by Derek Brown
@Jaromanda X is correct- you are looking for JSON.parse
. Something like this would suffice:
@Jaromanda X 是正确的-您正在寻找JSON.parse
. 像这样的东西就足够了:
responseArray = "[{"id":"blah", "type":"blah", ...}, {"id":"blah2",.... },...]"
<Item[]> JSON.parse(responseArray)
Obviously, this doesn't do any validation of the response (which is bad practice). You should ideally more some intense validation of the result:
显然,这不会对响应进行任何验证(这是不好的做法)。理想情况下,您应该对结果进行更深入的验证:
responseArray = "[{"id":"blah", "type":"blah", ...}, {"id":"blah2",.... },...]"
var result;
try {
itemListResponse = <Item[]>JSON.parse(responseArray);
if(!itemListResponse.has("id") ||
!itemListResponse.has("type") ||
!itemListResponse.has("state")){
throw "Invalid Item";
}
} catch (e){
}
Or, alternatively, use a JSON Schema validator like ajv.
或者,也可以使用像ajv这样的 JSON Schema 验证器。