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

ModuleAgda-2.7.0.1Haskell2010

Agda.Interaction.JSON

Encoding stuff into JSON values in TCM

  • 20 types
  • 15 classes
  • 80 values
  • PackageAgda-2.7.0.1
  • Exports115
  • LanguageHaskell2010
  • LicenceMIT
  • SourceJSON.hs
datadata Value
#

A JSON value represented as a Haskell value.

Instances38Eq, Data, Ord, Read, Show, IsString, …
datadata Options
#

Options that specify how to encode/decode your datatype to/from JSON.

Options can be set using record syntax on defaultOptions with the fields below.

Instances1Show
  • Show OptionsDefined in aeson-2.2.3.0 · Data.Aeson.Types.Internal

If True, record fields with a Nothing value will be omitted from the resulting object. If False, the resulting object will include those fields mapping to null.

In aeson-2.2 this flag is generalised to omit all values with omitField x = True. If False, the resulting object will include those fields encoded as specified.

Note that this does not affect parsing: Maybe fields are optional regardless of the value of omitNothingFields. allowOmittedFieds controls parsing behavior.

Applies only to Data.Aeson.FromJSON instances. If a field appears in the parsed object map, but does not appear in the target object, parsing will fail, with an error message indicating which fields were unknown.

value(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
#

Left-to-right composition of Kleisli arrows.

'(bs >=> cs) a' can be understood as the do expression

do b <- bs a
   cs b

or in terms of (>>=) as

bs a >>= cs
value(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
#

Right-to-left composition of Kleisli arrows. (>=>), with the arguments flipped.

Note how this operator resembles function composition (.):

(.)   ::            (b ->   c) -> (a ->   b) -> a ->   c
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
newtypenewtype Key
#
Instances27Eq, Data, Ord, Read, Show, IsString, …
valuedecode :: FromJSON a => ByteString -> Maybe a
#

Efficiently deserialize a JSON value from a lazy L.ByteString. If this fails due to incomplete or invalid input, Nothing is returned.

datadata Zero
#

A type-level indicator that ToJSON or FromJSON is being derived generically.

datadata One
#

A type-level indicator that ToJSON1 or FromJSON1 is being derived generically.

Instances12RecordToPairs, GToJSON', RecordFromJSON', GFromJSON, …
value(<?>) :: Parser a -> JSONPathElement -> Parser a
#

Add JSON Path context to a parser

When parsing a complex structure, it helps to annotate (sub)parsers with context, so that if an error occurs, you can find its location.

withObject "Person" $ \o ->
  Person
    <$> o .: "name" <?> Key "name"
    <*> o .: "age"  <?> Key "age"

(Standard methods like (.:) already do this.)

With such annotations, if an error occurs, you will get a JSON Path location of that error.

Since 0.10

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.

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.

Instances131ToJSON, …
datadata Series
#

A series of values that, when encoded, should be separated by commas. Since 0.11.0.0, the .= operator is overloaded to create either (Text, Value) or Series. You can use Series when encoding directly to a bytestring builder as in the following example:

toEncoding (Person name age) = pairs ("name" .= name <> "age" .= age)
Instances6Semigroup, Monoid, KeyValue, KeyValueOmit, KeyValuePair, FromPairs
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"
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 empty if the value cannot be converted to the desired type.

This differs from .:? by attempting to parse Null the same as any other JSON value, instead of interpreting it as Nothing.

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.

datadata FromArgs arity a where
#

A FromArgs value either stores nothing (for FromJSON) or it stores the three function arguments that decode occurrences of the type parameter (for FromJSON1).

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, …
classclass FromJSON1 (f :: Type -> Type) where
#

Lifting of the FromJSON class to unary type constructors.

Instead of manually writing your FromJSON1 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 liftParseJSON.

To use the second, simply add a deriving Generic1 clause to your datatype and declare a FromJSON1 instance for your datatype without giving a definition for liftParseJSON.

For example:

{-# LANGUAGE DeriveGeneric #-}

import GHC.Generics

data Pair a b = Pair { pairFst :: a, pairSnd :: b } deriving Generic1

instance FromJSON a => FromJSON1 (Pair a)

or

deriving via Generically1 (Pair a) instance FromJSON1 (Pair a)

If the default implementation doesn't give exactly the results you want, you can customize the generic decoding with only a tiny amount of effort, using genericLiftParseJSON with your preferred Options:

customOptions = defaultOptions
                { fieldLabelModifier = map toUpper
                }

instance FromJSON a => FromJSON1 (Pair a) where
    liftParseJSON = genericLiftParseJSON customOptions

Methods

Instances53FromJSON1, …
classclass FromJSON2 (f :: Type -> Type -> Type) where
#

Lifting of the FromJSON class to binary type constructors.

Instead of manually writing your FromJSON2 instance, Data.Aeson.TH provides Template Haskell functions which will derive an instance at compile time.

Methods

Instances21FromJSON2, …
classclass FromJSONKey a where
#

Read the docs for ToJSONKey first. This class is a conversion in the opposite direction. If you have a newtype wrapper around Text, the recommended way to define instances is with generalized newtype deriving:

newtype SomeId = SomeId { getSomeId :: Text }
  deriving (Eq,Ord,Hashable,FromJSONKey)

If you have a sum of nullary constructors, you may use the generic implementation:

data Color = Red | Green | Blue
  deriving Generic

instance FromJSONKey Color where
  fromJSONKey = genericFromJSONKey defaultJSONKeyOptions

Methods

Instances41FromJSONKey, …
datadata FromJSONKeyFunction a where
#

This type is related to ToJSONKeyFunction. If FromJSONKeyValue is used in the FromJSONKey instance, then ToJSONKeyValue should be used in the ToJSONKey instance. The other three data constructors for this type all correspond to ToJSONKeyText. Strictly speaking, FromJSONKeyTextParser is more powerful than FromJSONKeyText, which is in turn more powerful than FromJSONKeyCoerce. For performance reasons, these exist as three options instead of one.

Instances1Functor
classclass GFromJSON arity (f :: Type -> Type) where
#

Class of generic representation types that can be converted from JSON.

Instances7GFromJSON, …
classclass (ConstructorNames f, SumFromString f) => GFromJSONKey (f :: Type -> Type)
#
Instances1GFromJSONKey
  • (ConstructorNames f, SumFromString f) => GFromJSONKey fDefined in aeson-2.2.3.0 · Data.Aeson.Types.FromJSON
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"
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"
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"
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"
newtypenewtype DotNetTime
#

A newtype wrapper for UTCTime that uses the same non-standard serialization format as Microsoft .NET, whose System.DateTime type is by default serialized to JSON as in the following example:

/Date(1302547608878)/

The number represents milliseconds since the Unix epoch.

Constructors

Instances7Eq, Ord, Read, Show, FormatTime, FromJSON, …
datadata SumEncoding
#

Specifies how to encode constructors of a sum datatype.

Constructors

  • TaggedObject

    A constructor will be encoded to an object with a field tagFieldName which specifies the constructor tag (modified by the constructorTagModifier). If the constructor is a record the encoded record fields will be unpacked into this object. So make sure that your record doesn't have a field with the same label as the tagFieldName. Otherwise the tag gets overwritten by the encoded value of that field! If the constructor is not a record the encoded constructor contents will be stored under the contentsFieldName field.

  • UntaggedValue

    Constructor names won't be encoded. Instead only the contents of the constructor will be encoded as if the type had a single constructor. JSON encodings have to be disjoint for decoding to work properly.

    When decoding, constructors are tried in the order of definition. If some encodings overlap, the first one defined will succeed.

    Note: Nullary constructors are encoded as strings (using constructorTagModifier). Having a nullary constructor alongside a single field constructor that encodes to a string leads to ambiguity.

    Note: Only the last error is kept when decoding, so in the case of malformed JSON, only an error for the last constructor will be reported.

  • ObjectWithSingleField

    A constructor will be encoded to an object with a single field named after the constructor tag (modified by the constructorTagModifier) which maps to the encoded contents of the constructor.

  • TwoElemArray

    A constructor will be encoded to a 2-element array where the first element is the tag of the constructor (modified by the constructorTagModifier) and the second element the encoded contents of the constructor.

Instances2Eq, Show
valuecamelTo2 :: Char -> String -> String
#

Better version of camelTo. Example where it works better:

camelTo '_' "CamelAPICase" == "camel_apicase"
camelTo2 '_' "CamelAPICase" == "camel_api_case"
classclass GToJSON' enc arity (f :: Type -> Type) where
#

Class of generic representation types that can be converted to JSON.

Instances17GToJSON', …
classclass GetConName f => GToJSONKey (f :: k -> Type)
#
Instances1GToJSONKey
  • GetConName f => GToJSONKey fDefined in aeson-2.2.3.0 · Data.Aeson.Types.ToJSON
classclass KeyValue e kv | kv -> e where
#

A key-value pair for encoding a JSON object.

Methods

Instances3KeyValue
datadata ToArgs res arity a where
#

A ToArgs value either stores nothing (for ToJSON) or it stores the three function arguments that encode occurrences of the type parameter (for ToJSON1).

classclass ToJSON1 (f :: Type -> Type) where
#

Lifting of the ToJSON class to unary type constructors.

Instead of manually writing your ToJSON1 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 toJSON1.

To use the second, simply add a deriving Generic1 clause to your datatype and declare a ToJSON1 instance for your datatype without giving definitions for liftToJSON or liftToEncoding.

For example:

{-# LANGUAGE DeriveGeneric #-}

import GHC.Generics

data Pair a b = Pair { pairFst :: a, pairSnd :: b } deriving Generic1

instance ToJSON a => ToJSON1 (Pair a)

If the default implementation doesn't give exactly the results you want, you can customize the generic encoding with only a tiny amount of effort, using genericLiftToJSON and genericLiftToEncoding with your preferred Options:

customOptions = defaultOptions
                { fieldLabelModifier = map toUpper
                }

instance ToJSON a => ToJSON1 (Pair a) where
    liftToJSON     = genericLiftToJSON customOptions
    liftToEncoding = genericLiftToEncoding customOptions

See also ToJSON.

Methods

Instances55ToJSON1, …
classclass ToJSON2 (f :: Type -> Type -> Type) where
#

Lifting of the ToJSON class to binary type constructors.

Instead of manually writing your ToJSON2 instance, Data.Aeson.TH provides Template Haskell functions which will derive an instance at compile time.

The compiler cannot provide a default generic implementation for liftToJSON2, unlike toJSON and liftToJSON.

Methods

Instances21ToJSON2, …
classclass ToJSONKey a where
#

Typeclass for types that can be used as the key of a map-like container (like Map or HashMap). For example, since Text has a ToJSONKey instance and Char has a ToJSON instance, we can encode a value of type Map Text Char:

Example1 expression
LBC8.putStrLn $ encode $ Map.fromList [("foo" :: Text, 'a')]{"foo":"a"}

Since Int also has a ToJSONKey instance, we can similarly write:

Example1 expression
LBC8.putStrLn $ encode $ Map.fromList [(5 :: Int, 'a')]{"5":"a"}

JSON documents only accept strings as object keys. For any type from base that has a natural textual representation, it can be expected that its ToJSONKey instance will choose that representation.

For data types that lack a natural textual representation, an alternative is provided. The map-like container is represented as a JSON array instead of a JSON object. Each value in the array is an array with exactly two values. The first is the key and the second is the value.

For example, values of type '[Text]' cannot be encoded to a string, so a Map with keys of type '[Text]' is encoded as follows:

Example1 expression
LBC8.putStrLn $ encode $ Map.fromList [(["foo","bar","baz" :: Text], 'a')][[["foo","bar","baz"],"a"]]

The default implementation of ToJSONKey chooses this method of encoding a key, using the ToJSON instance of the type.

To use your own data type as the key in a map, all that is needed is to write a ToJSONKey (and possibly a FromJSONKey) instance for it. If the type cannot be trivially converted to and from Text, it is recommended that ToJSONKeyValue is used. Since the default implementations of the typeclass methods can build this from a ToJSON instance, there is nothing that needs to be written:

data Foo = Foo { fooAge :: Int, fooName :: Text }
  deriving (Eq,Ord,Generic)
instance ToJSON Foo
instance ToJSONKey Foo

That's it. We can now write:

Example2 expressions
let m = Map.fromList [(Foo 4 "bar",'a'),(Foo 6 "arg",'b')]LBC8.putStrLn $ encode m[[{"fooName":"bar","fooAge":4},"a"],[{"fooName":"arg","fooAge":6},"b"]]

The next case to consider is if we have a type that is a newtype wrapper around Text. The recommended approach is to use generalized newtype deriving:

newtype RecordId = RecordId { getRecordId :: Text }
  deriving (Eq,Ord,ToJSONKey)

Then we may write:

Example1 expression
LBC8.putStrLn $ encode $ Map.fromList [(RecordId "abc",'a')]{"abc":"a"}

Simple sum types are a final case worth considering. Suppose we have:

data Color = Red | Green | Blue
  deriving (Show,Read,Eq,Ord)

It is possible to get the ToJSONKey instance for free as we did with Foo. However, in this case, we have a natural way to go to and from Text that does not require any escape sequences. So ToJSONKeyText can be used instead of ToJSONKeyValue to encode maps as objects instead of arrays of pairs. This instance may be implemented using generics as follows:

instance ToJSONKey Color where
  toJSONKey = genericToJSONKey defaultJSONKeyOptions
Low-level implementations

The Show instance can be used to help write ToJSONKey:

instance ToJSONKey Color where
  toJSONKey = ToJSONKeyText f g
    where f = Text.pack . show
          g = text . Text.pack . show
          -- text function is from Data.Aeson.Encoding

The situation of needing to turning function a -> Text into a ToJSONKeyFunction is common enough that a special combinator is provided for it. The above instance can be rewritten as:

instance ToJSONKey Color where
  toJSONKey = toJSONKeyText (Text.pack . show)

The performance of the above instance can be improved by not using String as an intermediate step when converting to Text. One option for improving performance would be to use template haskell machinery from the text-show package. However, even with the approach, the Encoding (a wrapper around a bytestring builder) is generated by encoding the Text to a ByteString, an intermediate step that could be avoided. The fastest possible implementation would be:

-- Assuming that OverloadedStrings is enabled
instance ToJSONKey Color where
  toJSONKey = ToJSONKeyText f g
    where f x = case x of {Red -> "Red";Green ->"Green";Blue -> "Blue"}
          g x = case x of {Red -> text "Red";Green -> text "Green";Blue -> text "Blue"}
          -- text function is from Data.Aeson.Encoding

This works because GHC can lift the encoded values out of the case statements, which means that they are only evaluated once. This approach should only be used when there is a serious need to maximize performance.

Methods

  • toJSONKey :: ToJSONKeyFunction a

    Strategy for rendering the key for a map-like container.

  • toJSONKeyList :: ToJSONKeyFunction [a]

    This is similar in spirit to the showsList method of Show. It makes it possible to give String keys special treatment without using OverlappingInstances. End users should always be able to use the default implementation of this method.

Instances43ToJSONKey, …
valuedecodeFileStrict :: FromJSON a => FilePath -> IO (Maybe a)
#

Efficiently deserialize a JSON value from a file. If this fails due to incomplete or invalid input, Nothing is returned.

The input file's content must consist solely of a JSON document, with no trailing data except for whitespace.

This function parses immediately, but defers conversion. See json for details.

classclass EncodeTCM a where
#

The JSON version ofPrettyTCM, for encoding JSON value in TCM

Methods

Instances33EncodeTCM, …
value(.=) :: ToJSON a => Text -> a -> Pair
#

A key-value pair for encoding a JSON object.

Orphan instances

2 instances