I have a sum data type that looks like this:
data Declaration =
IndDecl { what :: String, name :: String, argnames :: Maybe [String], constructors :: [Constructor] }
| TypeDecl { what :: String, name :: String, argnames :: Maybe [String], value :: Maybe Arg }
| FixDecl { what :: String, fixlist :: Maybe [Fixitem] }
| TermDecl { what :: String, name :: String, typ :: Maybe Typ, value :: Maybe Arg }
deriving (Show, Eq)
And I'm deriving the JSON serializer/deserializer using Data.Aeson.TH
with the following options:
$(deriveJSON defaultOptions { sumEncoding = UntaggedValue } ''Declaration)
That removes the tag from the JSON construction. At the same time, I think my data already has a tag, which is the what
field. It can be one of the following:
IndDecl : "decl:ind"
FixDecl : "decl:fix"
etc. So the fact that I'm using an Untagged configuration for my JSON deserialized objects is kind of worrisome. How can I make Aeson derive JSON stubs based on the tags that my data already has?
Or maybe it's a better idea to remove the what
field and let Aeson add a "tag" field which describes the constructor?
EDIT: I tried the latter, by adding a tag field. Now it looks like:
-- Declarations
data Declaration =
IndDecl { what :: String, tag :: String, name :: String, argnames :: Maybe [String], constructors :: [Constructor] }
| TypeDecl { what :: String, tag :: String, name :: String, argnames :: Maybe [String], value :: Maybe Arg }
| FixDecl { what :: String, tag :: String, fixlist :: Maybe [Fixitem] }
| TermDecl { what :: String, tag :: String, name :: String, typ :: Maybe Typ, value :: Maybe Arg }
deriving (Show, Eq)
However, I get the following error:
Error in $.declarations[0]: key "tag" not present
Which I don't understand, since I created a "tag" field.
Data.Aeson.TH
documentation suggests you wantsumEncoding = defaultTaggedObject { tagFieldName = "what" }
to use your preexisting field as the tag. – duplodekey "tag" not present
even when I add a tag? (see EDIT) – rausted