parsing utctime with aeson

妖精的绣舞 提交于 2020-02-01 16:06:36

问题


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?


回答1:


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

Note the "pitfalls" section in the haddocks:

Note that the JSON standard requires that the top-level value be either an array or an object. If you try to use decode with a result type that is not represented in JSON as an array or object, your code will typecheck, but it will always "fail" at runtime:

...

So stick to objects (e.g. maps in Haskell) or arrays (lists or vectors in Haskell):



来源:https://stackoverflow.com/questions/19423533/parsing-utctime-with-aeson

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!