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:
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.
The itemListResponse is actually just a json string:
"[{"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.
@Jaromanda X is correct- you are looking for JSON.parse
. Something like this would suffice:
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 perform some 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With