我试图将对象序列化为JSON字符串并将其写入文件。将json写入Haskell中的文件(使用文本而不是[Char])
在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)
两个问题:
- 这似乎是一个字节串。我该如何处理?
- 如果这不是我想要做的,有没有一个Haskell json序列化解决方案使用文本而不是字符串,它还很简单?
有一种简单的方式来获得该版本Data.Aeson.Text的?似乎打破我的包: - 添加依赖关系时失败: aeson:需要(> = 1.0.0.0),无法解决其依赖关系 – Mittenchops
第二个给我: ''' *主要BS GHC。泛型TI> BS.writeFile “myfile2.json”(编码meowmers):23:30: 不能匹配预期类型 'BS.ByteString' 与实际类型 'Data.ByteString.Lazy.Internal.ByteString' NB:在'Data.ByteString.Internal'中定义'BS.ByteString' 'Data.ByteString.Lazy.Internal.ByteString' 在'Data.ByteString.Lazy.Internal' 中定义在第二个参数'BS.writeFile',即 '(编码meowmers)' 在表达式中:BS.writeFile“myfile2.json”(encode meowmers) ''' –
Mittenchops
对于第二种解决方案,尝试将import改为:import合格Data.ByteString.Lazy作为BS' – ErikR