2014-08-29 2 views
0

Github Webhooks API를 사용하는 앱을 작성 중입니다. 나는 목록을 반환 할 수있는 "수정"배열을 분석 할 수있는 방법AESON을 사용하여 중첩 JSON에서 Array를 읽는 방법

newtype CommitList = CommitList {commitList :: [Commit]} 

instance FromJSON CommitList where 
    parseJSON (Object o) = CommitList <$> o .: "commits" 
    parseJSON _ = mzero 

data Commit = Commit {ids :: String, message :: String, url :: String, modified :: [String], author :: Auth} deriving (Show) 

instance FromJSON Commit where 
    parseJSON (Object o) = Commit <$> o .: "id" <*> o .: "message" <*> o .: "url" <*> o .: "modified" <*> o .: "author" 
    parseJSON _ = mzero 

data Auth = Auth {name :: String, email :: String, username :: String} deriving (Show) 

instance FromJSON Auth where 
    parseJSON (Object o) = Auth <$> o .: "name" <*> o .: "email" <*> o .: "username" 
    parseJSON _ = mzero 

: http://organicorange.ro:8000/set

내가 이런 유형 선언을하고있는 중이 야 :이 JSON 구조를 가지고 후크 메시지에서 ?

+1

구현이 작동하지 않습니까? GHCi 테스트에'Auth' 섹션을 포함시키지 않았지만 이미'FromJSON a => FromJSON [a]'의 인스턴스가 있습니다. – bheklilr

+0

예, 코드를 복사/붙여 넣기하고 제공된 JSON 샘플을 사용하여 파싱을합니다. 당신의 질문은 정확히 무엇입니까? – bheklilr

+0

시간 내 주셔서 감사합니다. 이 구성에서 JSON에서 "수정 된"배열을 구문 분석하려고하면 [String []] [: [[ "src/FullBG/index.html", "src/Main.hs", "src/app .json "]]'내가 필요한 것은'["src/FullBG/index.html ","src/Main.hs ","src/app.json "]'같은 구성 요소를 가진 목록입니다. 덕분에 –

답변

1

나는 정말이 당신이 "어떻게 그 샘플 JSON 주어진 모든 수정 된 파일의 목록을 얻을 수 있습니다"요구하는 경우에 당신이 요구되지만, 무엇 확실하지,이 일을해야 해요 :

main = do 
    -- get the JSON from the api 
    json <- simpleHttp "http://organicorange.ro:8000/set" 
    -- parse and pull out the commits into [Commit], if the parse fails then you will just have am empty list 
    let commits = maybe ([]) (commitList) (decode json :: Maybe CommitList) 
    -- for each commit, pull out the modified files and then concatenate the results together 
    print $ concatMap (modified) commits 
+0

. 'concatMap'은 제가 찾고 있던 것입니다. –

+0

@DeckPope 미래에 [hoogle] (http://www.haskell.org/hoogle/?hoogle= [[a]) - % 3E [a])은 이러한 기능을 찾을 수있는 좋은 방법입니다. 이것이 실제로 귀하의 질문에 대답 한 경우 귀하는 답변을 수락 된 것으로 표시 할 수 있습니다. 또는 귀하의 질문에 여전히 답이 없다고 생각되면 알려주십시오. – jek

관련 문제