haskell / aeson

A fast Haskell JSON library
Other
1.25k stars 321 forks source link

Type-directed optional fields #1023

Closed friedbrice closed 1 year ago

friedbrice commented 1 year ago

This PR makes a backwards-compatible change to ToJSON and FromJSON that allows the instance to configure the optionality of record fields of that type when using Generic deriving or Template Haskell deriving.

Specifically, we make the following use-facing changes:

class ToJSON a where
    ...
    omitField :: a -> Bool
    omitField _ = False

and

class FromJSON a where
    ...
    omittedField :: Maybe a
    omittedField = Nothing

The new methods have default implementations that preserve the current behavior of Generically-derived and Template Haskell created instances. Instance authors can use these methods to configure how to represent fields of this type as omitted from a JSON record. As an added benefit, this PR eliminates the needs for special-case handling of Maybe and Option, significantly simplifying the Generic and Template Haskell code.

This PR solves https://github.com/haskell/aeson/issues/646 and https://github.com/haskell/aeson/issues/792, and it's similar to https://github.com/haskell/aeson/pull/839 by @phadej. Please let me know what you think, if this PR is a suitable addition to Aeson, and if there's anything about it you'd like me to fix or change.

Thanks much!

friedbrice commented 1 year ago

I was able to get the generic classes down to one method like you suggested. I still need to work on the ToJSON1 logic.

phadej commented 1 year ago

I marked this as draft.

Please ping when you seem happy again.

friedbrice commented 1 year ago

@phadej I'm pretty happy with it, now. I'm interested in your feedback :-)

friedbrice commented 1 year ago

Oh, also, @phadej, I do have some ideas about changes to To/FromJSON1, but I'd like to know more about what you have in mind before attempting that.

friedbrice commented 1 year ago

Could you squash your changes into own commit (and rebase on recent master), so I can continue from there.

Done. Thanks, @phadej !

phadej commented 1 year ago

@parsonsmatt

Some doc updates necessary,

If you think so please mark or even suggest amendments. I'm mostly happy with docs in this PR.

friedbrice commented 1 year ago

@phadej there were two places my docs had minor mistakes, but those were taken care of :-)

phadej commented 1 year ago

1039 is merged. Thanks for making the initial version!