Closed
Description
Is there a way to easily encode and decode records?
For instance, I have the following type:
newtype Register = Register { email :: String
, password :: String
}
I'd like to use purescript-generics for the encoding and decoding like below:
derive instance genericRegister :: Generic Register
instance encodeJsonRegister :: EncodeJson Register where
encodeJson = gEncodeJson
But when running the following code:
let register = Register { email: "email@email.com", password: "foobar" }
in show $ encodeJson res
I get the following output: {"values":[{"password":"foobar","email":"email@email.com"}],"tag":"Register"}
I was expecting the output to look like this: {"password":"foobar","email":"email@email.com"}
I tried to change the EncodeJson instance like the following:
instance encodeJsonRegister :: EncodeJson Register where
encodeJson (Register reg) = gEncodeJson reg
But that just gave me the following compiler error:
Error found:
Error in value declaration encodeJsonRegister:
Error at /opt/src/src/Main.purs line 44, column 1 - line 46, column 1:
Error in module Main:
No instance found for
Data.Generic.Generic { password :: String
, email :: String
}
The error makes sense, but I was hoping it would be easier to define encodeJson
for records. Is there an easy way? I don't want to have to write out something like this for every type:
instance encodeJsonRegister :: EncodeJson Register where
encodeJson (Register reg)
= "email" := reg.email
~> "password" := reg.password
~> jsonEmptyObject
Maybe I've just been spoiled by aeson
:-(
Metadata
Metadata
Assignees
Labels
No labels