使用 pipes-aeson 解析 JSON 的流

Parsing a stream of JSON with pipes-aeson

给出一个简单的例子JSON类型:

data Test = Test
  { name :: Text
  , age  :: Int
  } deriving (Show, Generic)

instance FromJSON Test

我如何使用 pipes-aeson 解码使用 decoded 镜头从套接字传来的 JSON 消息流?例如,我想在解析它们时将它们打印出来:

main = connect "127.0.0.1" "8000" $ \(socket, _) -> $ runEffect $
  some use of zoom decoded? view decoded? >-> P.print

decoded(来自 Pipes.Aeson.Unchecked 的那个)是一个镜头,它将原始字节的生产者转换为已解析的 FromJSON 值的生产者。

因此,我们必须首先使用 pipes-network 包中的 fromSocket 函数从套接字创建字节生产者。像这样:

-- to help with type inference
printTest :: (MonadIO m) => Consumer' Test m r
printTest = P.print

main = do
    connect "127.0.0.1" "8000" $ \(socket, _) -> $ runEffect $
        view decoded (fromSocket socket 4096) >-> printTest
    return ()