假设我想从http://reddit.com/r/haskell.json解析JSON
main = do
rsp <- simpleHTTP (getRequest "http://www.reddit.com/r/haskell.json")
str <- fmap (takeWhile isAscii) (getResponseBody rsp)
Run Code Online (Sandbox Code Playgroud)
我现在准备好要解析的字符串。但是,Aeson的decode函数具有以下类型签名:
decode :: FromJSON a =>
bytestring-0.10.0.2:Data.ByteString.Lazy.Internal.ByteString -> Maybe a
Run Code Online (Sandbox Code Playgroud)
如何从该字符串解码JSON?还是有更好的方法从GET请求解码?
simpleHTTP是多态的。所包含的响应主体可以是严格ByteString,懒惰ByteString或不安全的任何一个String。它选择其中之一来匹配Request ty传递给它的值。不幸的是,它HTTP是一个古老的库,维护不善-它几乎没有添加处理这三种类型所必需的多态性,但并不是在使库易于使用的所有地方。例如,使用getRequest强制响应为a String,使中的多态性无效simpleHTTP。
这是一个使用捕获该URL的内容HTTP并使用对其进行解码的最小工作示例aeson。
import Network.URI
import Network.HTTP
import Data.Aeson
-- There's absolutely no reason that this function shouldn't be in HTTP.
-- It's just as unsafe and terrible as getRequest is. In fact, this is a
-- strictly more general type than getRequest has, so there's no reason
-- it shouldn't just replace it.
getRequest_ :: HStream ty => String -> Request ty
getRequest_ s = let Just u = parseURI s in defaultGETRequest_ u
main :: IO ()
main = do
rsp <- simpleHTTP $ getRequest_ "http://www.reddit.com/r/haskell.json"
body <- getResponseBody rsp
print (decode $ body :: Maybe Value)
Run Code Online (Sandbox Code Playgroud)
请注意,这decode是最后固定在simpleHTTP那里的多态类型的用途。只是在此版本中,它与getRequest代码中有关类型的说明不同。
| 归档时间: |
|
| 查看次数: |
515 次 |
| 最近记录: |