I usually write my own ToJSON
and FromJSON
instances, but I decided to use deriveJSON
for a type because it was so simple:
data Priority = HIGH | MEDIUM | LOW deriving Show
$(deriveToJSON id ''Priority)
main = BS.putStrLn . encode $ HIGH
I would've expected the JSON
derivation to just write out the enum as a string. Instead, it's the key to a hash! {"HIGH":[]}
Why is this the default behavior?
It's because aeson
doesn't distinguish between sum types like your Priority
and more sophisticated types like data PriorityAndDetails = HIGH { highReason :: Text, alertType :: Alert } | MEDIUM { personResponsible :: Person } | LOW
. Fundamentally each of these types are "just a data constructor with n arguments".
In Priority
HIGH
, MED
, and LOW
are each just data constructors with zero arguments. In PriorityAndDetails
HIGH
, MED
, and LOW
are each just data constructors with some number of named arguments, 2, 1, and 0 respectively.
Generally I've found that you're likely to need to create your own ToJSON
and FromJSON
instances for anything besides early prototyping.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With