2013-12-12 32 views
3

我無法找到一個函數或變通方法來轉換字符串Data.ByteString.Lazy.Internal.ByteString哈斯克爾埃宋JSON圖書館字節字符串問題

一個在埃宋JSON庫的功能是decode,有如下描述:

decode :: FromJSON a => bytestring-0.10.0.2:Data.ByteString.Lazy.Internal.ByteString -> Maybe a 

我試過在Data.ByteString.Lazy.Char8中使用pack函數,但它返回一個不同的ByteString。任何人都知道如何解決這個問題?

以下是我工作的例子:

import Data.Aeson 
import Data.Text 
import Control.Applicative 
import Control.Monad (mzero) 
import qualified Data.ByteString.Lazy.Internal as BLI 
import qualified Data.ByteString.Lazy.Char8 as BSL 

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

instance FromJSON Person where 
    parseJSON (Object v) = Person <$> 
        v .: (pack "name") <*> 
        v .: (pack "age") 
    parseJSON _   = mzero 

我嘗試使用decode (BSL.pack "{\"name\":\"Joe\",\"age\":12}") :: Maybe Person ,並得到了以下錯誤消息:

Couldn't match expected type `bytestring-0.10.0.2:Data.ByteString.Lazy.Internal.ByteString' 
       with actual type `BSL.ByteString' 
    In the return type of a call of `BSL.pack' 
    In the first argument of `decode', namely 
     `(BSL.pack "{\"name\":\"Joe\",\"age\":12}")' 
    In the expression: 
     decode (BSL.pack "{\"name\":\"Joe\",\"age\":12}") :: Maybe Person 

幫助!

+2

你有多個版本的字符串安裝?嘗試運行'ghc-pkg list bytestring'來檢查。 – bennofs

+0

列表中出現了兩個字節bytestring-0.10.0.2和bytestring-.10.4.0 - 這是否會導致問題?我知道當我玩弄上面的代碼時,我有一個GHCI鏈接錯誤。 – MathanMV

+1

是的,我必須取消註冊bytestring-10.4.0才能使其正常工作。 – MathanMV

回答

5

你需要使用C2W(在Data.ByteString.Internal)

Data.ByteString.Lazy.pack $ map c2w "abcd" 

我寫出來的包還使用了正確的一個保證完全合格的名稱字符轉換爲Word8,但你可以清除此在進口部分。當我運行

> :t Data.ByteString.Lazy.pack $ map c2w "abcd" 

我得到「:: Data.ByteString.Lazy.Internal.ByteString」

記住Data.ByteString.Lazy代表數值的字符串(你甚至不能運行其包在字符串上,你需要提供一組數字「pack [1,2,3,4]」),所以你可能真的想使用char等價的Data.ByteString.Lazy.Char8。

+0

我設法得到正確的類型使用此。所以我得到Data.ByteString.Lazy.Internal.ByteString,但現在它要求byteString-0.10.0.2:Data.ByteString.Lazy.Internal.ByteString。嗯,我認爲這可能是一個問題bennofs評論原始文章,因爲我有兩個版本的字節串? – MathanMV

+0

這可能是一個版本問題,但請記住,即使在單個版本的庫中,也有四個字節 - strict/Word8,strict/Char8,懶/ Word8和嚴格/ Char8 ....並且只包直接在Char8版本的字符串上工作。 – jamshidh

+0

Brilliant在安裝兩個字節串時出現了另一個問題,如原始帖子中的評論中所述,該串也已被修復。謝謝! – MathanMV

0

您還可以使用方便fromStringData.ByteString.Lazy.UTF8utf8-string

這是一個與aeson用法相同的ByteString類型的函數模塊。它依賴於UTF8作爲緩衝區中使用的編碼。