0

I am writing an app that use the Github Webhooks API. In the hook message i got this JSON structure: http://organicorange.ro:8000/set

I am doing the type declaration like this:

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

How can I parse the "modified" array to return a list?

duplode
  • 33,731
  • 7
  • 79
  • 150
Deck Pope
  • 231
  • 3
  • 10
  • 1
    Does your implementation not work? I didn't include the `Auth` section in a GHCi test, but there's already an instance of `FromJSON a => FromJSON [a]`. – bheklilr Aug 29 '14 at 14:39
  • Yeah, I copy/pasted your code and used the sample JSON provided, it parses just fine. What exactly is your question? – bheklilr Aug 29 '14 at 14:48
  • thank you for your time. in this configuration when i try to parse the "modified" Array from the JSON i get [String] like i defined: `[["src/FullBG/index.html","src/Main.hs","src/app.json"]]` , what i need is a list with the components like `["src/FullBG/index.html","src/Main.hs","src/app.json"]`. – Deck Pope Aug 29 '14 at 19:50

1 Answers1

1

I am really not sure if this is what you are asking, but if you are asking "how can I, given that sample JSON, get a list of all modified files", then this should work:

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
jek
  • 563
  • 2
  • 9
  • @DeckPope No problem, in the future [hoogle](http://www.haskell.org/hoogle/?hoogle=[[a]]-%3E[a]) is a great way to find these functions. If this did indeed answer your question, then you may mark the answer as accepted, alternatively, if you feel your question remains yet unanswered, let me know. – jek Aug 30 '14 at 23:49