Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - how to parse JSON array into array of custom objects

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.

like image 868
CustardBun Avatar asked Nov 01 '17 03:11

CustardBun


1 Answers

@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.

like image 118
Derek Brown Avatar answered Sep 22 '22 11:09

Derek Brown