Search code examples
haskellaeson

Give a default value for fields not available in json using aeson


I am trying to load json using the Aeson library. The thing is that the datastructure that I want to load it into contains more fields than the json.

data Resource = Res {
                  name :: String,
                  file :: FilePath,
                  res :: Picture,
                  loaded :: Bool
                } deriving (Generic, Show)

Where only the name and the file fields are available in the json. Picture is a gloss Picture so that can't really be loaded from json.

I can't figure out how to leave out res and loaded out of the FromJSON instance.


Solution

  • If you can't load that structure from JSON, then don't define it this way! Make it

    data ResourceRef = ResRef
                    { name :: String
                    , file :: FilePath
                    } deriving (Generic, Show)
    

    That can be easily loaded from JSON. You can then have an additional

    data Resource = Res
                    { resName :: String
                    , resFile :: FilePath
                    , res :: Picture
                    } deriving (Generic, Show)
    

    ...which never gets in contact with JSON. And implement

    loadResource :: ResourceRef -> IO Resource