简体   繁体   English

如何在Haskell中将记录类型的值转换为JSON字符串?

[英]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? 我将如何将其转换为JSON对象甚至是String? (I'd like to hash it followingly) (我想在后面对其进行哈希处理)

You can easily do this with the Aeson library . 您可以使用Aeson库轻松完成此操作 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. 注意:如果仅出于计算hash的目的执行此操作,则JSON是不必要且效率低下的绕道。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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