我正在尝试解析一些JSON。
给出一个非常简单的[Object]
,如何在字符串键下获取Value
?
尝试一个(猜测):
d . key "test"
错误:
• Couldn't match expected type ‘Parser [Object]’
with actual type ‘(Value -> f0 Value) -> c0’
尝试两项(从阅读https://hackage.haskell.org/package/aeson-lens-0.5.0.0/docs/Data-Aeson-Lens.html开始):
d ^. key "test"
错误:
• Couldn't match expected type ‘Parser [Object]’
with actual type ‘Value’
完整代码:
{-# Language OverloadedStrings #-}
module JobManagerApi where
import Network.Wreq
import Job
import Control.Lens
import Data.Aeson
import Data.Aeson.Lens (_String, key)
import Data.Aeson.Types
import Data.ByteString.Lazy
-- parseResponse :: ByteString -> Either String String
parseResponse z = do
result <- eitherDecode z
flip parseEither result (\obj -> do
d <- obj .: "data"
-- k <- d . key "test"
return (d :: [Object])
)
apiPendingJobs :: IO [Job]
apiPendingJobs = do
r <- get "http://localhost:3000/user_job_queue"
let x = (r ^. responseBody)
print $ parseResponse x
pure []
相对而言:
flip parseEither result (\obj -> do
d <- obj .: "data"
-- k <- d . key
return (d :: [Object])
)
答案 0 :(得分:3)
d .: "test"
https://hackage.haskell.org/package/aeson-1.4.6.0/docs/Data-Aeson.html#v:.:
检索与对象的给定键关联的值。的 如果键不存在或值不能为空,则结果为空 转换为所需的类型。