Skip to content

easily encode/decode records #5

Closed
@cdepillabout

Description

@cdepillabout

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions