I'm using Aeson to accept user configuration in JSON format, where some fields may be omitted and the default values would be used. According to doc I should write something like this:
import Data.Aesonimport GHC.Genericsdata Person = Person { name :: String , age :: Int } deriving (Generic, Show)instance FromJSON Person where omittedField = Just $ Person "Unnamed" (-1) parseJSON = genericParseJSON defaultOptions { allowOmittedFields = True }main :: IO ()main = do print (eitherDecode @Person "{}") print (eitherDecode @Person "{\"name\":\"Bob\"}") print (eitherDecode @Person "{\"name\":\"Bob\",\"age\":42}")
Does not really work:
Left "Error in $: parsing Main.Person(Person) failed, key \"name\" not found"Left "Error in $: parsing Main.Person(Person) failed, key \"age\" not found"Right (Person {name = "Bob", age = 42})