2016-03-02 77 views
0

文件中讀取JSON這裏是我的代碼:試圖從使用埃宋

import Data.Aeson 
import Control.Applicative 
import Control.Monad 
import Data.Text 
import GHC.Generics 
import qualified Data.ByteString.Lazy as B 

data JSON' = 
    JSON' { 
     foo :: !Text, 
     int :: Int 
     } deriving (Show, Generic) 

instance FromJSON JSON' 
instance ToJSON JSON' 

jsonFile :: FilePath 
jsonFile = "test.json" 

getJSON :: IO B.ByteString 
getJSON = B.readFile jsonFile 

main :: IO() 
main = do 
    -- Get JSON data and decode it 
    d <- (eitherDecode <$> getJSON) :: IO (Either String [JSON']) 
    -- If d is Left, the JSON was malformed. 
    -- In that case, we report the error. 
    -- Otherwise, we perform the operation of 
    -- our choice. In this case, just print it. 
    case d of 
     Left err -> putStrLn err 
     Right ps -> print ps 

test.json看起來liket他:

-- test.json 
{ 
    "foo": "bar", 
    "int": 1 
} 

當我運行這段代碼我得到這個錯誤:

Can't make a derived instance of ‘Generic JSON'’: 
    You need DeriveGeneric to derive an instance for this class 
In the data declaration for ‘JSON'’ 

到目前爲止,Aeson的文檔與Hackage的所有文檔一樣,根本沒有幫助。我不知道我在做什麼錯。到目前爲止,我似乎正在將文件讀入字節串,將其轉換爲數據結構之類的「樹」,然後爲每個節點打印一個葉。我的代碼是直接從this link

我在做什麼錯?

Error in $: expected [a], encountered Object 

不知道這意味着什麼:

UPDATE

添加語言擴展申報文件

{-# LANGUAGE DeriveGeneriC#-} 

我得到這個錯誤後上方。

+0

你編輯的錯誤只是告訴你解碼期望一個JSON列表,所以test.json看起來像'[...]'而不是'{...}'。你的解碼器期望列表的原因是你的顯式類型'[JSON']'而不是'JSON',這將工作。 –

+0

你要求'[JSON']',但是提供一個JSON文件,其值爲'JSON''。也許你想在你的json文件中使用更多的方括號,或者在你的Haskell文件中使用更少的方括號。 –

回答

1

這個添加到文件

{-# LANGUAGE DeriveGeneriC#-} 

使用derive (Generic)是一個語言的擴展能力的頂部,你一定要告訴你希望這是打開GHC。

2

您需要將{-# LANGUAGE DeriveGeneriC#-}置於文件頂部。

在一個側面說明的aeson的文件說,

instance ToJSON Person where 
    -- ... 
    toEncoding = genericToEncoding defaultOptions 

instance FromJSON Person 
    -- No need to provide a parseJSON implementation. 

我想你大概也忘了toEncoding線在你ToJSON

+0

這個[link](https://www.schoolofhaskell.com/school/starting-with-haskell/libraries-and-frameworks/text-manipulation/json)能夠在不添加'toEncoding'函數的情況下讀取JSON – dopatraman

+0

添加擴展聲明後的事件我得到一個錯誤。請參閱修改。 – dopatraman

+0

在Data.Aeson文檔中使用'derived(Generic)'的每個示例均包含此語言雜注。 @dopatraman在「無幫助」文檔中應該提供哪些其他信息來幫助您? –