Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to base generic derived "ToJSON" key determination on typeclass #977

Open
clintonmead opened this issue Oct 26, 2022 · 1 comment
Open

Comments

@clintonmead
Copy link

Lets say I have something like following:

data Alice = T { x1 :: T1, x2 :: T2, ... , xn :: TN } deriving Generic 

class GetJSONKey t where
  getJSONKey :: Proxy t -> Key

instance GetJSONKey T1 where
  getJSONKey = fromString "z1"

instance GetJSONKey T2 where
  getJSONKey = fromString "z2"

.
.
.

instance GetJSONKey TN where
  getJSONKey = fromString "zn"

data Bob = T { y1 :: T1, y2 :: T2, ... , yn :: TN } deriving Generic 

Is there some way I can make both Alice and Bob have the same JSON serialisation result? As in, both with field names "z1" ... "zn", ignoring the field names in the records?

Basically, can I do deriving ToJSON but somehow leave the key selection up to a typeclass that is defined on all my fields, instead of it being based on the record names in the code itself (and hence able to be modified by otherwise innocent refactorings). Or am I going to need to explicitly list the columns here in a manual ToJSON instance?

@EggBaconAndSpam
Copy link

Have you considered enabling DuplicateRecordFields and simply having both Alice and Bob use the same field names "z1"..."zn"?

Otherwise I think it would be easier to write your own genericToJSON' using generics-sop rather than trying to hack genericToJSON into shape:

class GetJSONKey t where
  getJSONKey :: Key

genericRecordWithKeysToJSON :: forall a. (Generic a, RecordWithKeysToJSON (Code a)) => a -> Value
genericRecordWithKeysToJSON = Object . KeyMap.fromList . recordWithKeysToJSON @(Code a) . from @a

class RecordWithKeysToJSON (code :: [[Type]]) where
  recordWithKeysToJSON :: SOP I code -> [(Key, Value)]

instance RecordWithKeysToJSON' code => RecordWithKeysToJSON '[code] where
  recordWithKeysToJSON (SOP sop) = case sop of
    Z fields -> recordWithKeysToJSON' @code fields
    S xs -> case xs of {}

class RecordWithKeysToJSON' (code :: [Type]) where
  recordWithKeysToJSON' :: NP I code -> [(Key, Value)]

instance RecordWithKeysToJSON' '[] where
  recordWithKeysToJSON' Nil = []

instance
  (GetJSONKey t, RecordWithKeysToJSON' code, ToJSON t) =>
  RecordWithKeysToJSON' (t ': code)
  where
  recordWithKeysToJSON' (I x :* xs) = (getJSONKey @t, toJSON x) : recordWithKeysToJSON' @code xs

I would suggest DuplicateRecordFields ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants