5

我有一个复杂的嵌套 json,我试图用 Aeson 和 Attoparsec 将其解析为我的自定义类型。基于来自问题的信息:Haskell, Aeson & JSON parsing into custom typeAeson: How to convert Value into custom type?和一些来自互联网的信息。

当我使用以下代码时,我从重叠的 FromJSON 实例中获取“Nothing”值,但代码肯定会通过每个实例,我已经通过禁用其他一些实例来测试这一点。所以主要问题是:如何在实例中测试代码并查看 GHCi 中数据在执行过程中如何变化?

PS:尝试设置断点和“跟踪”,但它们仅在 main 和 parseCfg 函数中有效。

{-# 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's 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
4

1 回答 1

3

明显的问题是,在

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

第一个子句匹配所有输入,因此您的实例返回mzero任何参数。您应该更改子句的顺序。

当编译带有警告时,GHC 会告诉你重叠的模式。

于 2012-09-13T13:07:42.543 回答