aeson-pretty-0.7.2: JSON pretty-printing library and command-line tool.

Safe HaskellNone
LanguageHaskell98

Data.Aeson.Encode.Pretty

Contents

Description

Aeson-compatible pretty-printing of JSON Values.

Synopsis

Simple Pretty-Printing

encodePretty :: ToJSON a => a -> ByteString

A drop-in replacement for aeson's encode function, producing JSON-ByteStrings for human readers.

Follows the default configuration in defConfig.

encodePrettyToTextBuilder :: ToJSON a => a -> Builder

A drop-in replacement for aeson's encodeToTextBuilder function, producing JSON-ByteStrings for human readers.

Follows the default configuration in defConfig.

Pretty-Printing with Configuration Options

encodePretty' :: ToJSON a => Config -> a -> ByteString

A variant of encodePretty that takes an additional configuration parameter.

encodePrettyToTextBuilder' :: ToJSON a => Config -> a -> Builder

A variant of encodeToTextBuilder that takes an additional configuration parameter.

data Config

Constructors

Config 

Fields

confIndent :: Int

Indentation spaces per level of nesting

confCompare :: Text -> Text -> Ordering

Function used to sort keys in objects

defConfig :: Config

The default configuration: indent by four spaces per level of nesting, do not sort objects by key.

defConfig = Config { confIndent = 4, confCompare = mempty }

Sorting Keys in Objects

With the Aeson library, the order of keys in objects is undefined due objects being implemented as HashMaps. To allow user-specified key orders in the pretty-printed JSON, encodePretty' can be configured with a comparison function. These comparison functions can be composed using the Monoid interface. Some other useful helper functions to keep in mind are comparing and on.

Consider the following deliberately convoluted example, demonstrating the use of comparison functions:

An object might pretty-print as follows

{
  "baz": ...,
  "bar": ...,
  "foo": ...,
  "quux": ...,
}

which is clearly a confusing order of keys. By using a comparison function such as

comp :: Text -> Text -> Ordering
comp = keyOrder ["foo","bar"] `mappend` comparing length

we can achieve the desired neat result:

{
  "foo": ...,
  "bar": ...,
  "baz": ...,
  "quux": ...,
}

mempty :: Monoid a => a

Identity of mappend

Serves as an order-preserving (non-)sort function. Re-exported from Data.Monoid.

compare :: Ord a => a -> a -> Ordering

Sort keys in their natural order, i.e. by comparing character codes. Re-exported from the Prelude and Data.Ord

keyOrder :: [Text] -> Text -> Text -> Ordering

Sort keys by their order of appearance in the argument list.

Keys that are not present in the argument list are considered to be greater than any key in the list and equal to all keys not in the list. I.e. keys not in the argument list are moved to the end, while their order is preserved.