| Safe Haskell | None |
|---|---|
| Language | Haskell2010 |
Text.Format.Aeson
Contents
Description
Extend vformat to Aeson
The instance will try the following conditions one by one
when formatting Value:
- the arg is a
Number, useformatIntegerorformatRealFloatto format its value. - the arg is a
String, useformatStringto format its value. - the key is an empty key (i.e.
mempty), encode the wholeValueinto string, then useformatStringto format the string. - the arg is
Valueand the topmost key isIndex, get the element by the index, then format the element. - the arg is
Valueand the topmost key isName, get the value by the name, then format the value. - raise an
ArgKeyError.
If you have a ToJSON datatype, you can extend vformat to it directly,
or just convert it into Value (use toJSON) and then format the Value.
Example
>>>:set -XDeriveGeneric>>>import GHC.Generics>>>data Color = Red | Yellow | Blue deriving Generic>>>instance ToJSON Color>>>data Flag = Flag Color Int Int deriving Generic>>>instance ToJSON Flag>>>data Country = Country { name :: String, flag :: Flag } deriving Generic>>>instance ToJSON Country>>>let country = toJSON $ Country "X" $ Flag Blue 100 50>>>format1 "{name} {flag!0} {flag!1} {flag!2}" country"X Blue 100 50">>>format "{}" country"{\"flag\":[\"Blue\",100,50],\"name\":\"X\"}"