Aeson不会使用unicode字符解码字符串

Tet*_*igi 1 unicode haskell aeson

我正在尝试使用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\"}"
Run Code Online (Sandbox Code Playgroud)

在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
Run Code Online (Sandbox Code Playgroud)

有没有理由不解析带有unicode字符的String?我的印象是Haskell与unicode相当不错.任何建议将不胜感激!

谢谢,

tetigi

编辑

经过进一步调查后eitherDecode,我收到以下错误消息:

 *Main> test2
 Left "Failed reading: Cannot decode byte '\\x61': Data.Text.Encoding.decodeUtf8: Invalid UTF-8 stream"
Run Code Online (Sandbox Code Playgroud)

x61是'z'的unicode字符,它紧跟在特殊的unicode字符之后.不知道为什么它没有在特殊字符后读取字符!

改变test2test2 = decode $ pack "{ \"foo\": \"bòz\"}"不是给出了错误:

Left "Failed reading: Cannot decode byte '\\xf2': Data.Text.Encoding.decodeUtf8: Invalid UTF-8 stream"
Run Code Online (Sandbox Code Playgroud)

哪个是"ò"的字符,这更有意义.

Mic*_*man 6

问题是您使用Char8模块中的pack,它不适用于非Latin 1数据.而是encodeUtf8从文本中使用.