vformat-aeson-0.1.0.1: Extend vformat to Aeson datatypes

Safe HaskellNone
LanguageHaskell2010

Text.Format.Aeson

Contents

Description

Extend vformat to Aeson

The instance will try the following conditions one by one when formatting Value:

  1. the arg is a Number, use formatInteger or formatRealFloat to format its value.
  2. the arg is a String, use formatString to format its value.
  3. the key is an empty key (i.e. mempty), encode the whole Value into string, then use formatString to format the string.
  4. the arg is Value and the topmost key is Index, get the element by the index, then format the element.
  5. the arg is Value and the topmost key is Name, get the value by the name, then format the value.
  6. 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\"}"

Orphan instances