Here's my code:
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 looks liket his:
-- test.json
{
"foo": "bar",
"int": 1
}
When I run this code I get this error:
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'’
So far the documentation for Aeson, like all documentation on Hackage, is not helpful at all. I have no idea what I'm doing wrong. So far it seems like I'm reading a file into a bytestring, transforming it into a "tree" like data structure, and then printing one leaf per node. My code is straight from this link
What am I doing wrong?
UPDATE
After adding the language extension declaration to the top of the file
{-# LANGUAGE DeriveGeneric #-}
I'm getting this error:
Error in $: expected [a], encountered Object
Not sure what this means.
[ ... ]and not{ ... }. The reason your decoder expected a list is your explicit type[JSON']instead of justJSON', which would work.[JSON'], but provide a json file with a value of typeJSON'. Perhaps you wanted more square brackets in your json file or fewer in your Haskell file.