gpt4 book ai didi

haskell Data.Aeson.Value 到文本

转载 作者:行者123 更新时间:2023-12-02 12:31:23 25 4
gpt4 key购买 nike

data User = User { city :: Text
, country :: Text
, phone :: Text
, email :: Text}

instance ToJSON User where
toJSON (User a b c d)= object ["a" .= a
,"b" .= b
,"c" .= c
,"d" .= d]

test:: User -> IO Value
test u = do
let j = toJSON u
return j

我想要的是这样的文本

test::User -> IO Text
test u = do
let j = pack ("{\"city\":\"test\",\"country\":\"test\",\"phone\":\"test\",\"email\":\"test\"}")
return j

我不知道如何从值到文本

最佳答案

对于(我认为)普遍有用的功能来说,做到这一点比应该做的要困难。 Data.Aeson.Encode.encode 做了太多工作并将其一直转换为 ByteString

encode 开始并将 Lazy.Text -> ByteString 切换为 Lazy.Text -> Strict.Text 转换可以满足您的要求:

{-# LANGUAGE OverloadedStrings #-}

import Data.Aeson
import Data.Aeson.Text (encodeToTextBuilder)
import Data.Text
import Data.Text.Lazy (toStrict)
import Data.Text.Lazy.Builder (toLazyText)


data User = User
{ city :: Text
, country :: Text
, phone :: Text
, email :: Text
}

instance ToJSON User where
toJSON (User a b c d) = object
[ "city" .= a
, "country" .= b
, "phone" .= c
, "email" .= d
]

test :: User -> Text
test = toStrict . toLazyText . encodeToTextBuilder . toJSON

关于haskell Data.Aeson.Value 到文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11988853/

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