我们说我的记录类型看起来像这样
data Person = Person
{ name :: String,
age
} deriving (Show)
我如何将其转换为JSON对象甚至String? (我想随后哈希)
答案 0 :(得分:7)
您可以使用the Aeson library轻松完成此操作。事实上,这是完全他们给出的例子......有趣......
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
import Data.Aeson
import GHC.Generics
data Person = Person {
name :: String
, age :: Int
} deriving (Generic)
instance ToJSON Person
main :: IO ()
main = print $ encode (Person "Luke Morgenstern" 734)
注意:如果你只是为了计算哈希而执行此操作,那么JSON是一种不必要的低效绕道。最好直接去
{-# LANGUAGE DeriveGeneric #-}
import Data.Hashable
import GHC.Generics
data Person = Person {
name :: String
, age :: Int
} deriving (Generic)
instance Hashable Person
main :: IO ()
main = print $ hash (Person "Luke Morgenstern" 734)