haskell / haskell/aeson

Consider general `toJSON` `toEncoding` implementation

Open
#815 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Haskell
Stars
1.3k
Forks
336
Avg merge
3d 7h
Merged PRs (30d)
4

Description

I get fairly tired of implementing both `toJSON` and `toEncoding` for `ToJSON`, but it seems to me there's a solution, by extending the `KeyValue` concept a bit:
```haskell
-- So we can use Monoid KeyValue instances
instance KeyValue [Pair] where
k .= v = [k .= v]

class (KeyValue p, Monoid p) => JSONRep p r | r -> p, p -> r where
repJSON :: ToJSON a => a -> r
repPair :: Text -> r -> p
repObject :: p -> r
repList :: [r] -> r

instance JSONRep [Pair] Value where
repJSON = toJSON
repPair = (.=)
repObject = object
repList = toJSON

instance JSONRep Series Encoding where
repJSON = toEncoding
repPair = pair
repObject = pairs
repList = list id
```
(The names and specifics are just for example -- I'm sure there are better options and variations of `repList` etc.)

This would allow a single implementation for many things:
```haskell
myThingRep :: JSONRep p r => MyThing -> r
myThingRep t = repObject
$ "thing" J..= thing t
<> "values" `repPair` repList (map valueRep $ values t)

instance ToJSON MyThing where
toJSON = myThingRep
toEncoding = myThingRep
```
Thoughts? Improvements? (I'd prefer to do this with a TypeFamily for `p` but not sure how to get the constraints right.)

Contributor guide

Open the contributing guide

Research direction

Start by reviewing the ToJSON, toJSON, toEncoding, KeyValue, Series, and Encoding APIs referenced in the issue. Compare the proposed JSONRep abstraction with the existing approach and determine a concrete, accepted API change; completion is not defined because the issue remains an open design discussion.

Written by the indexing model from the issue text.

Assessment

Tech stack
haskell
Domain
backend-api-design
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.