>>-6ren">
gpt4 book ai didi

json - 将 json 写入 Haskell 中的文件(使用 Text 而不是 [Char])

转载 作者:行者123 更新时间:2023-12-03 14:39:51 25 4
gpt4 key购买 nike

我正在尝试将对象序列化为 JSON 字符串并将其写入文件。

在python中,我会做类似的事情:

>>> meowmers = {"name" : "meowmers", "age" : 1}
>>> import json
>>> with open("myfile.json","wb") as f
json.dump(meowmers, f)

$ cat myfile.json
{"age": 1, "name": "meowmers"}

我在 Haskell 看这个
$ stack ghci

{-# LANGUAGE OverloadedStrings #-}
:set -XOverloadedStrings

import GHC.Generics
import Data.Aeson as A
import Data.Text.Lazy as T
import Data.Text.Lazy.IO as I

:{
data Cat = Cat {
name :: Text
, age :: Int
} deriving Show
:}

let meowmers = Cat {name = "meowmers", age = 1}
writeFile "myfile.json" (encode meowmers)

不好了!
*A T I GHC.Generics> I.writeFile "myfile2.json" (encode meowmers)

<interactive>:34:29:
Couldn't match expected type ‘Text’
with actual type ‘bytestring-0.10.6.0:Data.ByteString.Lazy.Internal.ByteString’
In the second argument of ‘I.writeFile’, namely ‘(encode meowmers)’
In the expression: I.writeFile "myfile2.json" (encode meowmers)

两个问题:
  • 这似乎是一个字节串。我该如何处理?
  • 如果那不是我想要做的,是否有一个使用 Text 而不是 String 的 Haskell json 序列化解决方案,但相当简单?
  • 最佳答案

    所以,把一切都解决掉(因为大部分工作已经完成)。你实际上有两个问题:

  • 您正在混合字符串类型
  • 您没有 ToJSON 的实例为 Cat 声明

  • 这是一个依赖于 aeson 最新版本的工作示例和 text (对我来说是 aeson-1.0.0.0text-1.2.2.1
    {-# LANGUAGE OverloadedStrings, DeriveGeneric, DeriveAnyClass #-}

    import GHC.Generics
    import Data.Text.Lazy (Text)
    import Data.Text.Lazy.IO as I
    import Data.Aeson.Text (encodeToLazyText)
    import Data.Aeson (ToJSON)

    data Cat = Cat { name :: Text, age :: Int } deriving (Show, Generic, ToJSON)

    meowmers = Cat { name = "meowmers", age = 1 }

    main = I.writeFile "myfile.json" (encodeToLazyText meowmers)

    正如您可能从导入中看出的那样,我依赖 aeson通过 encodeToLazyText 在字符串类型之间进行转换.这涉及第 1 个问题。

    然后,我使用语言扩展名 DeriveGeneric获取 Generic Cat 的实例,并将其与扩展名 DeriveAnyClass 结合使用获取 ToJSON 的实例对于 Cat .该实例的魔力再次为 part of aeson .

    运行这个,我得到一个新文件 myfile.json包含 {"age":1,"name":"meowmers"}在里面。

    关于json - 将 json 写入 Haskell 中的文件(使用 Text 而不是 [Char]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39090784/

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