Haskell Aeson:如何在 IO monad 中从 Parser 中获取价值

Haskell Aeson: How to get value out of Parser in IO monad

我正尝试在 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 aa:

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"