我正在嘗試撰寫一個FromJSON實作來決議物件串列,同時跳過其中的一些 - 那些包含特定 json 屬性的物件。
我有這樣的代碼,但如果沒有正確處理 mzero,它會在遇到帶有“exclude: true”的值時回傳錯誤。
newtype Response = Response [Foo]
newtype Foo = Foo Text
instance FromJSON Response where
parseJSON = withArray "Foos" $ \arr -> do
-- can I filter out here the ones which return `mzero`?
foos <- mapM parseJSON arr
pure $ Response (toList foos)
instance FromJSON Foo where
parseJSON = withObject "Foo" $ \foo -> do
isExcluded <- foo .: "exclude"
if isExcluded
then mzero
else do
pure $ Foo "bar"
我發現了一些提示使用 的問題parseMaybe,但我不知道如何從FromJSON定義中使用它,它似乎更適合從“外部”運行決議器。是否可以跳過“內部”?還是我走錯路了?
uj5u.com熱心網友回復:
您正在尋找的是可選功能。找到它可能有點棘手,因為它非常通用,而不僅僅是aeson. 為了您的目的,它將具有型別Parser a -> Parser (Maybe a)并與catMaybesshould 一起使用,以執行您想要的操作。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/537530.html
標籤:哈斯克尔永生
上一篇:Haskell:價值函式
下一篇:Haskell實體函式
