我有一个复杂的嵌套json,我试图用Aeson和Attoparsec解析我的自定义类型。基于问题的信息:Haskell, Aeson & JSON parsing into custom type,Aeson: How to convert Value into custom type?以及来自互联网的一些信息。
当我使用以下代码时,我从重叠的FromJSON实例获得“Nothing”值,但代码肯定会通过每个实例,我已经通过禁用其他一些问题对此进行了测试。所以主要问题:如何在实例中测试代码,看看数据如何在GHCi中执行变更?
P.S:试图设置断点和“跟踪”,但它们仅在主要和& 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
答案 0 :(得分:3)
显而易见的问题是
instance FromJSON CProperty where
parseJSON _ = mzero
parseJSON (Object o) = ...
第一个子句匹配所有输入,因此无论参数是什么,您的实例都会返回mzero
。你应该改变条款的顺序。
在使用警告进行编译时,GHC会告诉您重叠模式。