Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

Set default values for omitted fields with Haskell Aeson

$
0
0

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})

Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>