我正在尝试编写一个从 api 解析 xml、剥离一些信息并将结果打印为 json 的模块,但我在打印步骤中遇到了问题。如果我打印节目,我确实看到那里有正确的数据,但是,应该将记录转换为 json, 的调用encode shows
会产生段错误。
{-# LANGUAGE Arrows, NoMonomorphismRestriction, OverloadedStrings #-}
import Network.HTTP
import Text.XML.HXT.Core
import Data.Aeson
import qualified Data.ByteString.Lazy.Char8 as LazyByteString
openUrl :: String -> IO String
openUrl url = getResponseBody =<< simpleHTTP (getRequest url)
composeSearch :: String -> String
composeSearch query = "http://services.tvrage.com/feeds/search.php?show=" ++ urlEncode query
searchShow :: String -> IO String
searchShow query = openUrl $ composeSearch query
data TvShow = TvShow { showName, showId :: String } deriving (Show)
getShow = deep (isElem >>> hasName "show") >>>
proc x -> do
name <- getText <<< getChildren <<< deep (hasName "name") -< x
id <- getText <<< getChildren <<< deep (hasName "showid") -< x
returnA -< TvShow { showName = name, showId = id }
instance ToJSON TvShow where
toJSON (TvShow name id) = object ["name" .= name, "id" .= id]
main :: IO ()
main = do
results <- searchShow "Always Sunny"
shows <- runX (readString [ withValidate no ] results >>> getShow)
putStrLn (LazyByteString.unpack (encode shows))
编辑:正如 user1891025 所指出的,这可能是我的机器或软件包版本的问题。
- 系统:Ubuntu 11.04 32bit
- 爱生 v0.6.1.0
- GHC v7.2.1
这个问题越来越具体,所以我会把它带到 irc,但如果有人有任何帮助,请告诉我!