12

I can't get aeson to parse an UTCTime value. I tried to encode one and feed it back, but that didn't work:

Prelude Data.Aeson Data.Time.Clock> getCurrentTime >>= (print . encode)
"\"2013-10-17T09:42:49.007Z\""
Prelude Data.Aeson Data.Time.Clock> decode "2013-10-17T09:42:49.007Z" :: Maybe UTCTime
Nothing
Prelude Data.Aeson Data.Time.Clock> decode "\"2013-10-17T09:42:49.007Z\"" :: Maybe UTCTime
Nothing

The FromJSON instance of the UTCTime type is the following (ref):

instance FromJSON UTCTime where
    parseJSON = withText "UTCTime" $ \t ->
        case parseTime defaultTimeLocale "%FT%T%QZ" (unpack t) of
          Just d -> pure d
          _      -> fail "could not parse ISO-8601 date"

following the format description found here, everything should be ok. What am I missing?

4

1 回答 1

18
Prelude Data.Aeson Data.Time> decode (encode [x]) :: Maybe [UTCTime]
Just [2013-10-17 10:06:59.542 UTC]

请注意黑线鳕中的“陷阱”部分:

请注意,JSON 标准要求顶级值是数组或对象。如果您尝试使用未在 JSON 中表示为数组或对象的结果类型的 decode,您的代码将进行类型检查,但它在运行时总是“失败”:

...

所以坚持使用对象(例如 Haskell 中的地图)或数组(Haskell 中的列表或向量):

于 2013-10-17T10:11:04.187 回答