【发布时间】:2014-12-27 16:57:37
【问题描述】:
我正在尝试使用 Data.Aeson (https://hackage.haskell.org/package/aeson-0.6.1.0/docs/Data-Aeson.html) 来解码一些 JSON 字符串,但是它无法解析包含非标准字符的字符串。
例如,文件:
import Data.Aeson
import Data.ByteString.Lazy.Char8 (pack)
test1 :: Maybe Value
test1 = decode $ pack "{ \"foo\": \"bar\"}"
test2 :: Maybe Value
test2 = decode $ pack "{ \"foo\": \"bòz\"}"
在 ghci 中运行时,给出以下结果:
*Main> :l ~/test.hs
[1 of 1] Compiling Main ( /Users/ltomlin/test.hs, interpreted )
Ok, modules loaded: Main.
*Main> test1
Just (Object fromList [("foo",String "bar")])
*Main> test2
Nothing
是否有理由不使用 unicode 字符解析字符串?我的印象是 Haskell 对 unicode 非常好。任何建议将不胜感激!
谢谢,
特提吉
编辑
在使用eitherDecode 进行进一步调查后,我收到以下错误消息:
*Main> test2
Left "Failed reading: Cannot decode byte '\\x61': Data.Text.Encoding.decodeUtf8: Invalid UTF-8 stream"
x61 是 'z' 的 unicode 字符,紧跟在特殊的 unicode 字符之后。不知道为什么它无法读取特殊字符之后的字符!
将 test2 改为 test2 = decode $ pack "{ \"foo\": \"bòz\"}" 会出现错误:
Left "Failed reading: Cannot decode byte '\\xf2': Data.Text.Encoding.decodeUtf8: Invalid UTF-8 stream"
“ò”是哪个字,比较有道理。
【问题讨论】:
-
你真的用过aeson-0.6.1.0吗?话虽如此,这似乎是
Text和ByteString之间的一些错误编码。您是否尝试过使用encodeUtf8 :: Text -> ByteString(来自Data.Text.Encoding)对文本进行编码? -
@Zeta 我刚刚链接了我当时打开的选项卡 - 安装的版本是 0.7.0.4。我试试看!
-
@Zeta 成功了!我现在得到
Right (Object fromList [("foo",String "b\242r")]):)