aeson icon indicating copy to clipboard operation
aeson copied to clipboard

deriveToJSON: Allow injecting extra fields via Options (for e.g. JSON-LD)

Open akhra opened this issue 10 years ago • 0 comments

JSON-LD specifies a number of descriptive tags which are intended to be injected as metadata into JSON objects (nice example here). A lot of it is stuff there's no reason to store in the local data representation (effectively type info, really). Beyond that, the names of the tags are supposed to start with @, which kills clever work-arounds involving fieldLabelModifier.

Unless I've missed something (very possible), there's no good way to reflect this in derived aeson instances. I believe a simple "good enough" solution would be to expand Options with something like unionObject:

data Foo = Foo { bar :: String }
fooLD = object ["@type" .= ("Foo"::String)]
$(deriveJSON defaultOptions{unionObject = fooLD} ''Foo)

> encode $ Foo "baz"
"{\"@type\":\"Foo\",\"bar\":\"baz\"}"

There are some cases like the @language tag where this is insufficient, but it seems like an easy and safe (in terms of not getting in the way of better stuff later) solution to a lot of problems.

akhra avatar Sep 25 '15 03:09 akhra