我正在尝试通过以下示例在JSON
中构建Haskell
:
module Main where
import GHC.Exts
import Data.Aeson
import qualified Data.Text.Lazy.IO as T
import qualified Data.Text.Lazy.Encoding as T
val :: Value
val = Object $ fromList [
("numbers", Array $ fromList [Number 1, Number 2, Number 3]),
("boolean", Bool True) ]
main :: IO ()
main = T.putStrLn . T.decodeUtf8 . encode $ val
当我尝试编译时,编译器抱怨:
• Couldn't match type ‘[Char]’ with ‘Data.Text.Internal.Text’
Expected type: Item Object
Actual type: ([Char], Value)
• In the expression: ("boolean", Bool True)
In the first argument of ‘fromList’, namely
‘[("numbers", Array $ fromList [Number 1, Number 2, ....]),
("boolean", Bool True)]’
In the second argument of ‘($)’, namely
‘fromList
[("numbers", Array $ fromList [Number 1, Number 2, ....]),
("boolean", Bool True)]’
|
12 | ("boolean", Bool True) ]
| ^^^^^^^^^^^^^^^^^^^^^^
答案 0 :(得分:7)
您需要将OverloadedStrings
扩展名放在文件顶部:
#!/usr/bin/env stack
-- stack script --resolver lts-12.7
{-# LANGUAGE OverloadedStrings #-}
import Data.Aeson
import qualified Data.Text.Lazy.Encoding as T
import qualified Data.Text.Lazy.IO as T
import GHC.Exts
val :: Value
val =
Object $
fromList
[ ("numbers", Array $ fromList [Number 1, Number 2, Number 3])
, ("boolean", Bool True)
]
main :: IO ()
main = T.putStrLn . T.decodeUtf8 . encode $ val
并执行它们:
$ stack fuse.hs
{"boolean":true,"numbers":[1,2,3]}
要了解使其生效的原因,请refer to this answer。
答案 1 :(得分:6)
您收到的错误是关于错误的字符串表示形式。 Haskell有很多,例如ByteString
(严格或延迟),Text
(严格或延迟),String
([Char]
的别名)。最后一个是默认值,也是大多数时候应该避免的那个值。
Aeson库使用Text
作为字符串表示形式。您可以在字符串前使用T.pack
来修复代码(将其转换为文本),如下所示:
val :: Value
val =
Object $
fromList
[ (T.pack "numbers", Array $ fromList [Number 1, Number 2, Number 3])
, (T.pack "boolean", Bool True)
]
或者您可以仅启用OverloadedStrings
扩展名。开启时,Haskell编译器将尝试确定应使用哪种字符串表示形式。只需将{-# LANGUAGE OverloadedStrings #-}
放在文件的顶部即可。