简体   繁体   中英

How can one turn a value of a record type into a JSON String in Haskell?

Let's say I have record type that looks like this

data Person = Person
  { name :: String,
    age
  } deriving (Show)

How would I go around turning this into a JSON Object or even String? (I'd like to hash it followingly)

You can easily do this with the Aeson library . In fact, this is exactly the example they give... interesting...

{-# 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)

Note: if you do this only for the purpose of calculating a hash , then JSON is an unneeded and inefficient detour. Better go directly

{-# 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM