gpt4 book ai didi

json - 将记录中的构造函数转换为 aeson haskell 中的自定义 json 字符串

转载 作者:行者123 更新时间:2023-12-04 18:33:54 26 4
gpt4 key购买 nike

我想将我的 json 转换为以下格式。并从以下格式转换为我的记录。请检查我在下面写的代码。

{
"uid" : "bob",
"emailid" : "bob@bob.com",
"email_verified" : "Y" // "Y" for EmailVerified and "N" for EmailNotVerified
}

我有下面的代码,我试图将用户类型与 json 相互转换
在 Haskell 中使用 Aeson 库
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}

import Data.Monoid ((<>))
import GHC.Generics
import Data.Aeson (FromJSON, ToJSON)
import Data.Aeson.Types

data User = User {
userId :: String,
userEmail :: String,
userEmailVerified :: EmailState
} deriving (Show, Generic)

data EmailState = EmailVerified | EmailNotVerified deriving (Generic, Show)

instance ToJSON User where
toJSON u = object [
"uid" .= userId u,
"emailid" .= userEmail u,
"email_verified" .= userEmailVerified u
]

instance FromJSON User where
parseJSON = withObject "User" $ \v -> User
<$> v .: "uid"
<*> v .: "emailid"
<*> v .: "email_verified"

instance ToJSON EmailState
instance FromJSON EmailState

但是,我目前能够生成的格式如下
{
"uid" : "bob",
"emailid" : "bob@bob.com",
"email_verified" : "EmailVerified"
}

最佳答案

您需要实现 ToJSONEmailState你自己(所以删除 instance ToJSON EmailState ,并写成这样):

instance ToJSON EmailState where
toJSON EmailVerified = String "Y"
toJSON EmailNotVerified = String "N"

您还需要更改解析器:
instance FromJSON EmailState where
parseJSON (String "Y") = return EmailVerified
parseJSON (String "N") = return EmailNotVerified
parseJSON _ = fail "Invalid JSON value to parse"

关于json - 将记录中的构造函数转换为 aeson haskell 中的自定义 json 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47508894/

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