2

我正在使用这段代码:

{-# LANGUAGE OverloadedStrings #-}

import Data.Aeson
import Data.Maybe
import Data.ByteString.Lazy
import Control.Applicative
import Debug.Trace
import Control.Monad
import qualified Data.Aeson.Types as T

main = do
  res <- liftA show (liftA decodeOriginal (Data.ByteString.Lazy.readFile "./a.json"))
  Prelude.putStrLn res

interpretResult :: Maybe String -> String
interpretResult Nothing = "Error."
interpretResult x = fromJust x

data TotalLine1 = TotalLine1 {
  timestamp :: Integer,
  value :: Integer
} deriving (Eq, Show)

data Original = Original {
  totals :: [TotalLine1]
} deriving (Eq, Show)

instance FromJSON Original where
  parseJSON (Object v) = traceStack "Original" (Original <$> (parseJSON =<< (v .: "visitors.total")))
  parseJSON _ = mzero

instance FromJSON TotalLine1 where
  parseJSON (Object v) = TotalLine1 <$>
                         v .: "timestamp" <*>
                         v .: "value"
decodeOriginal :: ByteString -> Maybe Original
decodeOriginal b = traceStack "decoding" (do
  a <- decode b :: Maybe Original
  return a)

尝试像这样解析 JSON:

{
visitors.total: [
{
timestamp: 1365548400,
value: 1
},
{
timestamp: 1365548700,
value: 2
},
{
timestamp: 1365549000,
value: 5
},
]
}

但是 main 每次都返回 Nothing 。我做错了什么?似乎连 parseJSON 都没有被称为 Original。

4

1 回答 1

5

您的 JSON 文件无效。

一方面,必须引用字段的名称,

"timestamp"

等等,另一方面,TotalLine1s 列表中有一个尾随逗号,这会导致对ByteStringa的解码Value失败。引用字段名称并删除结尾的逗号,它可以工作。

于 2013-04-11T23:09:15.633 回答