如何使用 Aeson 的解析器从非常简单的对象中获取键值
How to get value from key using Aeson's Parser from very simple Object`
我正在尝试解析一些 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])
)
d .: "test"
https://hackage.haskell.org/package/aeson-1.4.6.0/docs/Data-Aeson.html#v:.:
Retrieve the value associated with the given key of an Object. The
result is empty if the key is not present or the value cannot be
converted to the desired type.
我正在尝试解析一些 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])
)
d .: "test"
https://hackage.haskell.org/package/aeson-1.4.6.0/docs/Data-Aeson.html#v:.:
Retrieve the value associated with the given key of an Object. The result is empty if the key is not present or the value cannot be converted to the desired type.