文件中讀取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#-}
我得到這個錯誤後上方。
你編輯的錯誤只是告訴你解碼期望一個JSON列表,所以test.json看起來像'[...]'而不是'{...}'。你的解碼器期望列表的原因是你的顯式類型'[JSON']'而不是'JSON',這將工作。 –
你要求'[JSON']',但是提供一個JSON文件,其值爲'JSON''。也許你想在你的json文件中使用更多的方括號,或者在你的Haskell文件中使用更少的方括號。 –