2017-11-01 2 views
2

나는이 공간에 비교적 새로운 편이므로 잘못된 용어를 사용하고 있으면 사과드립니다. 설명을 요청하십시오. (다소) 외부 서비스를 호출 할 때TypeScript - 사용자 정의 객체의 배열로 JSON 배열을 구문 분석하는 방법

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 
} 

ItemResponse 채운 올바르게 :

결과는 ItemResponses의 인

는 좀 타이프 인터페이스를 갖는다. 지금은 ItemResponse 배열의 크기가 1이지만 itemListResponse 배열에 여러 Items가 있다고 가정합니다.

"[{"id":"blah", "type":"blah", ...}, {"id":"blah2",.... },...]" 

가 어떻게 항목의 배열로 변환합니다 :

itemListResponse 실제로 단지 JSON 문자열인가?

저는 JSON을 단일 객체로 파싱하는 것에 익숙하지만, 배열을 사용하여이를 수행하는 방법에 익숙하지 않다고 생각합니다.

+1

** 제목 **을 의미있게 만들면 시작할 수 있습니다.하지만 JSON 구문 분석을 사용하여 JSON을 구문 분석 할 수 있습니다. –

+0

[쉼표로 배열 변환] (https://stackoverflow.com/questions) 중복 가능성 있음/13272406/convert-string-with-commas-to-array) – Manish

+1

@Manish는 중복되지 않습니다. –

답변

2

@Jaromanda X는 정확합니다. JSON.parse을 찾고 있습니다. 이런 식으로 뭔가가 충분 :

responseArray = "[{"id":"blah", "type":"blah", ...}, {"id":"blah2",.... },...]" 
<Item[]> JSON.parse(responseArray) 

물론,이 (나쁜 관행) 응답의 유효성 검사를하지 않습니다. 당신은해야 결과의 이상적보다 약간 강한 검증 :

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){ 

} 

또는 대안 ajv 같은 JSON 스키마 유효성 검사기를 사용합니다.

관련 문제