16

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.

3
  • 1
    you could start by making your title meaningful - but you might want JSON.parse to parse JSON Commented Nov 1, 2017 at 3:45
  • Possible duplicate of Convert string with commas to array Commented Nov 1, 2017 at 3:48
  • 4
    @Manish not a duplicate. Commented Nov 1, 2017 at 4:13

1 Answer 1

17

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.