gpt4 book ai didi

haskell 埃森 : How to get value out of Parser in IO monad

转载 作者:行者123 更新时间:2023-12-02 18:23:41 26 4
gpt4 key购买 nike

我正在尝试在 IO 中进行 JSON 解析:

{-# LANGUAGE OverloadedStrings #-}
import Network.HTTP.Simple
import Data.Aeson
import Data.Maybe (fromJust)

main :: IO ()
main = do
response <- getResponseBody <$> httpJSON "http://localhost:9200" :: IO Object
name <- fromJust <$> response .: "name" :: Parser String
print "hi"

我收到错误:

/home/nut/dev/haskell/elastic/app/Main.hs:39:11: error:
• Couldn't match type ‘Parser’ with ‘IO’
Expected type: IO String
Actual type: Parser String
• In a stmt of a 'do' block:

那么如何从 json 结果中获取该 name 呢?

最佳答案

Aeson 有一堆函数可以从 Parser a 转换为 a:

parse       :: (a -> Parser b) -> a -> Result b
parseEither :: (a -> Parser b) -> a -> Either String b
parseMaybe :: (a -> Parser b) -> a -> Maybe b

所以如果你有例如

(.: "name") :: Object -> Parser String

那么你就有了

parseMaybe (.: "name") :: Object -> Maybe String

这样你就可以做到

{-# LANGUAGE OverloadedStrings #-}
import Network.HTTP.Simple
import Data.Aeson
import Data.Maybe (fromJust)
import Data.Aeson.Types -- new import for parseMaybe

main :: IO ()
main = do
response <- getResponseBody <$> httpJSON "http://localhost:9200"
let name = fromJust $ parseMaybe (.: "name") response :: String
print "hi"

关于 haskell 埃森 : How to get value out of Parser in IO monad,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40752365/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com