haskell 使用Aeson解析json对象数组时跳过某些项

vfwfrxfs  于 2022-11-24  发布在  其他
关注(0)|答案(1)|浏览(117)

我正在尝试编写一个FromJSON实现,它将解析一个对象列表,同时跳过其中的一些对象-那些包含特定json属性的对象。
我有这样的代码,但是如果没有正确处理mzero,一旦遇到带有"exclude:真"。

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定义中使用它,它似乎更适合从"外部"运行解析器。是否可以跳过"内部"?或者我在这里走错了路?

q3qa4bjr

q3qa4bjr1#

你要找的是可选函数。它可能有点难找,因为它是非常通用的,而不仅仅是aeson中的一个辅助函数。为了你的目的,它将具有Parser a -> Parser (Maybe a)类型,并与catMaybes一起使用,应该可以完成你想要的任务。

相关问题