使用Aeson从Haskell中的URL解析JSON数据

时间:2015-04-29 11:06:05

标签: json haskell aeson

我试图在Haskell中创建一个从URL获取一些JSON输入的Web应用程序。

{-# 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 个答案:

答案 0 :(得分:1)

在目前的格式中,您的代码只能解析表单{"date":"2015-04-12T20:36:25+00:00", "temperature":7}的一行:它会尝试将输入解析为Temperatures,但无法找到{{1}键入根对象,因为它只有一个date键。

问题是您的temperatures数据类型与您的输入不匹配。这是应该匹配的东西:

Temperatures