haskell/aeson

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

Open

#294 建立於 2015年9月25日

在 GitHub 查看
 (0 留言) (4 反應) (0 負責人)Haskell (334 fork)batch import
help wanted

倉庫指標

Star
 (1,298 star)
PR 合併指標
 (平均合併 935天 9小時) (30 天內合併 5 個 PR)

描述

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.

貢獻者指南