2015-04-29 89 views
0

我試圖在Haskell中創建一個Web應用程序,該應用程序需要來自URL的一些JSON輸入。使用Aeson解析來自Haskell中的URL的JSON數據

{-# LANGUAGE OverloadedStrings, DeriveGeneriC#-} 

import Data.Aeson as Q 
import Data.Text 
import Control.Applicative 
import Control.Monad 
import qualified Data.ByteString.Lazy as B 
import Network.HTTP.Conduit (simpleHttp) 
import GHC.Generics 
--import Data.DateTime 

data Temperatures = 
    Temperatures { date :: String 
       , temperature :: Int 
       } deriving (Show, Generic) 

instance FromJSON Temperatures 
instance ToJSON Temperatures 


jsonURL :: String 
jsonURL = "http://www.phoric.eu/temperature" 

getJSON :: IO B.ByteString 
getJSON = simpleHttp jsonURL 


main :: IO() 
main = do 
d <- (eitherDecode <$> getJSON) :: IO (Either String Temperatures) 
case d of 
    Left e -> putStrLn e 
    Right stuff -> print stuff 

但是,我得到的運行時錯誤:

Bradley$ runhaskell test.hs 
The key "date" was not found 

的JSON低於@這是在代碼的URL。

{"temperatures":[ 
    {"date":"2015-02-28T20:16:12+00:00", "temperature":0}, 
    {"date":"2015-01-01T21:46:55+00:00", "temperature":2}, 
    {"date":"2015-04-08T21:46:53+00:00", "temperature":3}, 
    {"date":"2015-04-09T21:46:01+00:00", "temperature":4}, 
    {"date":"2015-04-10T21:46:40+00:00", "temperature":5}, 
    {"date":"2015-04-11T21:46:36+00:00", "temperature":6}, 
    {"date":"2015-04-12T20:36:25+00:00", "temperature":7} 
]} 

我不知道爲什麼當它們明確存在於JSON對象中時,它不能識別鍵,有什麼想法?

回答

1

在其目前的形式,你的代碼只能解析形式{"date":"2015-04-12T20:36:25+00:00", "temperature":7}單行:它試圖將輸入解析爲Temperatures,卻找不到一個date鑰匙插入根對象,因爲它只有一個temperatures鍵。

問題是您的Temperatures數據類型與您的輸入不匹配。這是應該匹配的東西:

data DataPoint = DataPoint { date :: String 
          , temperature :: Int 
          } deriving (Show, Generic) 

data Temperatures = Temperatures { temperatures :: [DataPoint] 
           } deriving (Show, Generic)