2014-08-29 71 views
0

我正在編寫一個使用Github Webhooks API的應用程序。 在掛機消息我得到這個JSON結構:http://organicorange.ro:8000/set我怎樣才能讀取嵌套的JSON數組使用AESON

我做的類型聲明是這樣的:

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 

如何可以解析了「修改」數組返回一個列表?

+1

你的執行不起作用嗎?我沒有在GHCi測試中包含'Auth'部分,但已經有'FromJSON a => FromJSON [a]'的實例。 – bheklilr 2014-08-29 14:39:03

+0

是的,我複製/粘貼你的代碼,並使用提供的示例JSON,它解析得很好。你的問題到底是什麼? – bheklilr 2014-08-29 14:48:12

+0

感謝您的時間。在這個配置中,當我嘗試從JSON解析「modified」數組時,我得到[String]就像我定義的那樣:'[[「src/FullBG/index.html」,「src/Main.hs」,「src/app .json「]]',我需要的是像'[」src/FullBG/index.html「,」src/Main.hs「,」src/app.json「]這樣的組件的列表。 – 2014-08-29 19:50:17

回答

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'就是我一直在尋找的東西。 – 2014-08-30 08:06:32

+0

@DeckPope沒問題,將來[hoogle](http://www.haskell.org/hoogle/?hoogle= [[a]] - %3E [a])是找到這些功能的好方法。如果這確實回答了您的問題,那麼您可以將答案標記爲已接受,或者,如果您覺得您的問題尚未解答,請告訴我。 – jek 2014-08-30 23:49:25