0

我正在编写一个使用 Github Webhooks API 的应用程序。在钩子消息中,我得到了这个 JSON 结构:http ://organicorange.ro:8000/set

我正在做这样的类型声明:

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

如何解析“修改”数组以返回列表?

4

1 回答 1

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
于 2014-08-30T00:08:28.843 回答