HORIZON HASKELLDocslts/ghc-9.10.x248f8f02026-10-05Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · 248f8f0 · 2026-10-05

Moduleyaml-0.11.11.2Haskell2010

Data.Yaml

Provides a high-level interface for processing YAML files.

This module reuses most of the infrastructure from the aeson package. This means that you can use all of the existing tools for JSON processing for processing YAML files. As a result, much of the documentation below mentions JSON; do not let that confuse you, it's intentional.

For the most part, YAML content translates directly into JSON, and therefore there is very little data loss. If you need to deal with YAML more directly (e.g., directly deal with aliases), you should use the Text.Libyaml module instead.

For documentation on the aeson types, functions, classes, and operators, please see the Data.Aeson module of the aeson package.

Look in the examples directory of the source repository for some initial pointers on how to use this library.

  • 9 types
  • 2 classes
  • 39 values
  • Packageyaml-0.11.11.2
  • Exports51
  • LanguageHaskell2010
  • LicenceBSD-3-Clause
  • SourceYaml.hs

Encoding

4 declarations

Decoding

5 declarations

Decoding multiple documents

For situations where we need to be able to parse multiple documents separated by --- in a YAML stream, these functions decode a list of values rather than a single value.

More control over decoding

Types

8 declarations
datadata Value
#

A JSON value represented as a Haskell value.

Instances37Eq, Data, Ord, Read, Show, IsString, …
newtypenewtype Parser a
#

A JSON parser. N.B. This might not fit your usual understanding of "parser". Instead you might like to think of Parser as a "parse result", i.e. a parser to which the input has already been applied.

Instances9Monad, Functor, MonadFix, MonadFail, Applicative, Alternative, …
datadata ParseException
#
Instances2Show, Exception

Alternative to show to display a ParseException on the screen. Instead of displaying the data constructors applied to their arguments, a more textual output is returned. For example, instead of printing:

InvalidYaml (Just (YamlParseException {yamlProblem = "did not find expected ',' or '}'", yamlContext = "while parsing a flow mapping", yamlProblemMark = YamlMark {yamlIndex = 42, yamlLine = 2, yamlColumn = 12}})))

It looks more pleasant to print:

YAML parse exception at line 2, column 12,
while parsing a flow mapping:
did not find expected ',' or '}'

Since 0.8.11

Constructors and accessors

6 declarations
valueobject :: [Pair] -> Value
#

Create a Value from a list of name/value Pairs. If duplicate keys arise, later keys and their associated values win.

value(.:) :: FromJSON a => Object -> Key -> Parser a
#

Retrieve the value associated with the given key of an Object. The result is empty if the key is not present or the value cannot be converted to the desired type.

This accessor is appropriate if the key and value must be present in an object for it to be valid. If the key and value are optional, use .:? instead.

value(.:?) :: FromJSON a => Object -> Key -> Parser (Maybe a)
#

Retrieve the value associated with the given key of an Object. The result is Nothing if the key is not present or if its value is Null, or empty if the value cannot be converted to the desired type.

This accessor is most useful if the key and value can be absent from an object without affecting its validity. If the key and value are mandatory, use .: instead.

value(.!=) :: Parser (Maybe a) -> a -> Parser a
#

Helper for use in combination with .:? to provide default values for optional JSON object fields.

This combinator is most useful if the key and value can be absent from an object without affecting its validity and we know a default value to assign in that case. If the key and value are mandatory, use .: instead.

Example usage:

 v1 <- o .:? "opt_field_with_dfl" .!= "default_val"
 v2 <- o .:  "mandatory_field"
 v3 <- o .:? "opt_field2"

With helpers (since 0.8.23)

valuewithText :: String -> (Text -> Parser a) -> Value -> Parser a
#

withText name f value applies f to the Text when value is a Data.Aeson.String and fails otherwise.

Error message example
withText "MyType" f Null
-- Error: "parsing MyType failed, expected String, but encountered Null"
valuewithArray :: String -> (Array -> Parser a) -> Value -> Parser a
#

withArray expected f value applies f to the Array when value is an Array and fails otherwise.

Error message example
withArray "MyType" f (String "oops")
-- Error: "parsing MyType failed, expected Array, but encountered String"
valuewithScientific :: String -> (Scientific -> Parser a) -> Value -> Parser a
#

withScientific name f value applies f to the Scientific number when value is a Data.Aeson.Number and fails using typeMismatch otherwise.

Warning: If you are converting from a scientific to an unbounded type such as Integer you may want to add a restriction on the size of the exponent (see withBoundedScientific) to prevent malicious input from filling up the memory of the target system.

Error message example
withScientific "MyType" f (String "oops")
-- Error: "parsing MyType failed, expected Number, but encountered String"
valuewithBool :: String -> (Bool -> Parser a) -> Value -> Parser a
#

withBool expected f value applies f to the Bool when value is a Boolean and fails otherwise.

Error message example
withBool "MyType" f (String "oops")
-- Error: "parsing MyType failed, expected Boolean, but encountered String"

Parsing

3 declarations
valueparseMonad :: MonadFail m => (a -> Parser b) -> a -> m b
#

Deprecated. With the MonadFail split, this function is going to be removed in the future. Please migrate to parseEither.

Classes

2 declarations
classclass ToJSON a where
#

A type that can be converted to JSON.

Instances in general must specify toJSON and should (but don't need to) specify toEncoding.

An example type and instance:

-- Allow ourselves to write Text literals.
{-# LANGUAGE OverloadedStrings #-}

data Coord = Coord { x :: Double, y :: Double }

instance ToJSON Coord where
  toJSON (Coord x y) = object ["x" .= x, "y" .= y]

  toEncoding (Coord x y) = pairs ("x" .= x <> "y" .= y)

Instead of manually writing your ToJSON instance, there are two options to do it automatically:

  • Data.Aeson.TH provides Template Haskell functions which will derive an instance at compile time. The generated instance is optimized for your type so it will probably be more efficient than the following option.

  • The compiler can provide a default generic implementation for toJSON.

To use the second, simply add a deriving Generic clause to your datatype and declare a ToJSON instance. If you require nothing other than defaultOptions, it is sufficient to write (and this is the only alternative where the default toJSON implementation is sufficient):

{-# LANGUAGE DeriveGeneric #-}

import GHC.Generics

data Coord = Coord { x :: Double, y :: Double } deriving Generic

instance ToJSON Coord where
    toEncoding = genericToEncoding defaultOptions

or more conveniently using the DerivingVia extension

deriving via Generically Coord instance ToJSON Coord

If on the other hand you wish to customize the generic decoding, you have to implement both methods:

customOptions = defaultOptions
                { fieldLabelModifier = map toUpper
                }

instance ToJSON Coord where
    toJSON     = genericToJSON customOptions
    toEncoding = genericToEncoding customOptions

Previous versions of this library only had the toJSON method. Adding toEncoding had two reasons:

  1. toEncoding is more efficient for the common case that the output of toJSON is directly serialized to a ByteString. Further, expressing either method in terms of the other would be non-optimal.

  2. The choice of defaults allows a smooth transition for existing users: Existing instances that do not define toEncoding still compile and have the correct semantics. This is ensured by making the default implementation of toEncoding use toJSON. This produces correct results, but since it performs an intermediate conversion to a Value, it will be less efficient than directly emitting an Encoding. (this also means that specifying nothing more than instance ToJSON Coord would be sufficient as a generically decoding instance, but there probably exists no good reason to not specify toEncoding in new instances.)

Methods

  • toJSON :: a -> Value

    Convert a Haskell value to a JSON-friendly intermediate type.

  • toEncoding :: a -> Encoding

    Encode a Haskell value as JSON.

    The default implementation of this method creates an intermediate Value using toJSON. This provides source-level compatibility for people upgrading from older versions of this library, but obviously offers no performance advantage.

    To benefit from direct encoding, you must provide an implementation for this method. The easiest way to do so is by having your types implement Generic using the DeriveGeneric extension, and then have GHC generate a method body as follows.

    instance ToJSON Coord where
        toEncoding = genericToEncoding defaultOptions
    
  • toJSONList :: [a] -> Value
  • toEncodingList :: [a] -> Encoding
  • omitField :: a -> Bool

    Defines when it is acceptable to omit a field of this type from a record. Used by (.?=) operator, and Generics and TH deriving with omitNothingFields = True.

Instances113ToJSON, …
classclass FromJSON a where
#

A type that can be converted from JSON, with the possibility of failure.

In many cases, you can get the compiler to generate parsing code for you (see below). To begin, let's cover writing an instance by hand.

There are various reasons a conversion could fail. For example, an Object could be missing a required key, an Array could be of the wrong size, or a value could be of an incompatible type.

The basic ways to signal a failed conversion are as follows:

  • fail yields a custom error message: it is the recommended way of reporting a failure;

  • empty (or mzero) is uninformative: use it when the error is meant to be caught by some (<|>);

  • typeMismatch can be used to report a failure when the encountered value is not of the expected JSON type; unexpected is an appropriate alternative when more than one type may be expected, or to keep the expected type implicit.

prependFailure (or modifyFailure) add more information to a parser's error messages.

An example type and instance using typeMismatch and prependFailure:

-- Allow ourselves to write Text literals.
{-# LANGUAGE OverloadedStrings #-}

data Coord = Coord { x :: Double, y :: Double }

instance FromJSON Coord where
    parseJSON (Object v) = Coord
        <$> v .: "x"
        <*> v .: "y"

    -- We do not expect a non-Object value here.
    -- We could use empty to fail, but typeMismatch
    -- gives a much more informative error message.
    parseJSON invalid    =
        prependFailure "parsing Coord failed, "
            (typeMismatch "Object" invalid)

For this common case of only being concerned with a single type of JSON value, the functions withObject, withScientific, etc. are provided. Their use is to be preferred when possible, since they are more terse. Using withObject, we can rewrite the above instance (assuming the same language extension and data type) as:

instance FromJSON Coord where
    parseJSON = withObject "Coord" $ \v -> Coord
        <$> v .: "x"
        <*> v .: "y"

Instead of manually writing your FromJSON instance, there are two options to do it automatically:

  • Data.Aeson.TH provides Template Haskell functions which will derive an instance at compile time. The generated instance is optimized for your type so it will probably be more efficient than the following option.

  • The compiler can provide a default generic implementation for parseJSON.

To use the second, simply add a deriving Generic clause to your datatype and declare a FromJSON instance for your datatype without giving a definition for parseJSON.

For example, the previous example can be simplified to just:

{-# LANGUAGE DeriveGeneric #-}

import GHC.Generics

data Coord = Coord { x :: Double, y :: Double } deriving Generic

instance FromJSON Coord

or using the DerivingVia extension

deriving via Generically Coord instance FromJSON Coord

The default implementation will be equivalent to parseJSON = genericParseJSON defaultOptions; if you need different options, you can customize the generic decoding by defining:

customOptions = defaultOptions
                { fieldLabelModifier = map toUpper
                }

instance FromJSON Coord where
    parseJSON = genericParseJSON customOptions

Methods

Instances113FromJSON, …

Custom encoding

9 declarations
valueisSpecialString :: Text -> Bool
#

Determine whether a string must be quoted in YAML and can't appear as plain text. Useful if you want to use setStringStyle.

Set the string style in the encoded YAML. This is a function that decides for each string the type of YAML string to output.

WARNING: You must ensure that special strings (like "yes"/"no"/"null"/"1234") are not encoded with the Plain style, because then they will be decoded as boolean, null or numeric values. You can use isSpecialString to detect them.

By default, strings are encoded as follows:

datadata FormatOptions
#

Contains options relating to the formatting (indendation, width) of the YAML output.

Deprecated

3 declarations
valuedecode :: FromJSON a => ByteString -> Maybe a
#

Deprecated. Please use decodeEither or decodeThrow, which provide information on how the decode failed