gpt4 book ai didi

haskell - Aeson 中的解码结果为“无”

转载 作者:行者123 更新时间:2023-12-02 05:08:05 26 4
gpt4 key购买 nike

我正在使用这段代码:

{-# 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。我做错了什么?似乎甚至没有为 Original 调用 parseJSON。

最佳答案

您的 JSON 文件无效。

一方面,字段名要加引号,

"timestamp"

等另一方面,TotalLine1 列表中有一个尾随逗号,这会导致将 ByteString 解码为 Value 失败.引用字段名称并删除尾随的逗号,它起作用了。

关于haskell - Aeson 中的解码结果为“无”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15960176/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com