Haskell, Aeson - how to debug instances?

I have a complex nested json that I am trying to parse with Aeson and Attoparsec into my custom types. Based on the information from the questions: Haskell, Aeson and JSON are parsed into a user type , Aeson: How to convert a value to a non-standard? and some data from the Internet.

When I use the following code, I get the value "Nothing" from the overlaid FromJSON instance, but the code goes through each instance for sure, I checked this by disabling some other insances. So, the main question : how to check the code in the examples and see how the data changes during execution in GHCi?

PS: I tried to set breakpoints and "trace", but they work only in the main and parseCfg-functions.

{-# LANGUAGE OverloadedStrings, FlexibleInstances #-}

-- high level data
data Cfg = Cfg { nm  :: CProperty,
             author :: CProperty,
             langs :: CValue,
             grops :: CListArr,
             projs :: CPropArr
           } deriving (Show)

...

instance FromJSON CProperty where
parseJSON _          = mzero
parseJSON (Object o) = CProperty <$> toCProperty o
  where
    toCProperty :: (HM.HashMap T.Text Value) -> J.Parser (T.Text, T.Text)
    toCProperty _  = error "unexpected property"
    toCProperty o' = do
      l <- return $ HM.toList o'
      k <- return $ fst $ head l
      v <- return $ snd $ head l
      v' <- parseJSON v
      return $ (k, v')

... lot of different instances

-- |this instance is specific for different files
-- based on common functions to work with most of nested json code
instance FromJSON Cfg where
  parseJSON _          = mzero
  parseJSON (Object o) = do
    nm     <- (parseJSON :: Value -> J.Parser CProperty) =<< (o .: T.pack "Name")
    autor  <- (parseJSON :: Value -> J.Parser CValue)    =<< (o .: T.pack "Author")
    langs  <- (parseJSON :: Value -> J.Parser CProperty) =<< (o .: T.pack "Languages")
    groups <- (parseJSON :: Value -> J.Parser CListArr)  =<< (o .: T.pack "Groups")
    projs  <- (parseJSON :: Value -> J.Parser CPropArr)  =<< (o .: T.pack "Projects")
    return $ Cfg nm author langs groups projs
------------------------------------------------------------------------------------

main :: IO ()
main = do:
  s <- L.readFile "/home/config.json"
  -- print $ show s
  let cfg =  parseCfg s
  print $ show $ cfg

parseCfg :: L.ByteString -> Maybe Cfg
parseCfg s = decode s
+5
source share
1 answer

The obvious problem is that in

instance FromJSON CProperty where
    parseJSON _          = mzero
    parseJSON (Object o) = ...

the first sentence matches all inputs, so your instance returns mzeroregardless of the argument. You must reorder the offers.

When compiling with warnings, the GHC will tell you about overlapping patterns.

+2
source

All Articles