Safe Haskell | None |
---|---|
Language | Haskell2010 |
- A json specification for any type
- Construct specifications for records
- Construct specifications for sum types
- Construct specifications for enum types
- Shared between specifications for simplicity
- Generate json serializers/encoders and parsers from specs
- Specification structures
- Aeson reexports
- Implementation detail structures
Synopsis
- data HighSpec a (ty :: SpecType) as = HighSpec {
- hs_name :: !Text
- hs_description :: !(Maybe Text)
- hs_bodySpec :: !(BodySpec ty a as)
- data SpecType
- recSpec :: (IsDataSpec q, DContainer q ~ RecordFields) => Text -> Maybe Text -> HVectElim (DFields q) (DType q) -> q -> RecordTypeSpec (DType q) (DFields q)
- type RecordTypeSpec t flds = HighSpec t 'SpecRecord flds
- reqField :: FromJSON f => Text -> (t -> f) -> RecordField t f
- (.=) :: FromJSON f => Text -> (t -> f) -> RecordField t f
- optField :: FromJSON f => Text -> (t -> Maybe f) -> RecordField t (Maybe f)
- (.=?) :: FromJSON f => Text -> (t -> Maybe f) -> RecordField t (Maybe f)
- sumSpec :: (IsDataSpec q, DContainer q ~ SumOptions) => Text -> Maybe Text -> q -> SumTypeSpec (DType q) (DFields q)
- type SumTypeSpec t flds = HighSpec t 'SpecSum flds
- sumOpt :: Text -> Prism' t o -> SumOption t o
- (.->) :: Text -> Prism' t o -> SumOption t o
- enumSpec :: (IsDataSpec q, DContainer q ~ PhantomEnumContainer) => Text -> Maybe Text -> q -> EnumTypeSpec (DType q) (DFields q)
- type EnumTypeSpec t flds = HighSpec t 'SpecEnum flds
- enumOpt :: Text -> Prism' t () -> EnumOption t
- (@->) :: Text -> Prism' t () -> EnumOption t
- class IsDataSpec t where
- type DFields t :: [*]
- type DType t
- type DContainer t :: * -> [*] -> *
- compileRec :: t -> DContainer t (DType t) (DFields t)
- data a :& b = a :& b
- jsonSerializer :: AllHave ToJSON as => HighSpec a ty as -> a -> Value
- jsonEncoder :: AllHave ToJSON as => HighSpec a ty as -> a -> Encoding
- jsonParser :: AllHave FromJSON as => HighSpec a ty as -> Value -> Parser a
- data BodySpec ty a as where
- BodySpecRecord :: !(RecordSpec a as) -> BodySpec 'SpecRecord a as
- BodySpecSum :: !(SumSpec a as) -> BodySpec 'SpecSum a as
- BodySpecEnum :: !(EnumSpec a) -> BodySpec 'SpecEnum a as
- data RecordField t f = RecordField {
- rf_jsonKey :: !Text
- rf_optional :: !Bool
- rf_jsonLoader :: Object -> Text -> Parser f
- rf_get :: !(t -> f)
- data RecordSpec a fs = RecordSpec {
- rs_make :: HVect fs -> a
- rs_fields :: RecordFields a fs
- data RecordFields t fs where
- RFEmpty :: RecordFields t '[]
- (:+:) :: RecordField t f -> RecordFields t fs -> RecordFields t (f ': fs)
- data SumOption t o = SumOption {
- so_jsonKey :: !Text
- so_prism :: !(Prism' t o)
- data SumSpec a os = SumSpec {
- ss_options :: SumOptions a os
- data SumOptions t os where
- SOEmpty :: SumOptions t '[]
- (:|:) :: SumOption t o -> SumOptions t os -> SumOptions t (o ': os)
- data EnumOption t = EnumOption {
- eo_jsonKey :: !Text
- eo_prism :: !(Prism' t ())
- data EnumSpec a = EnumSpec {
- es_options :: [EnumOption a]
- class ToJSON a where
- toJSON :: a -> Value
- toEncoding :: a -> Encoding
- toJSONList :: [a] -> Value
- toEncodingList :: [a] -> Encoding
- class FromJSON a where
- newtype PhantomEnumContainer t (ts :: [*]) = PhantomEnumContainer {
- unPhantomEnumContainer :: [EnumOption t]
- class CombinableContainer t where
- combineContainer :: t a (as :: [*]) -> t a (bs :: [*]) -> t a (Append as bs)
A json specification for any type
data HighSpec a (ty :: SpecType) as Source #
HighSpec | |
|
Construct specifications for records
recSpec :: (IsDataSpec q, DContainer q ~ RecordFields) => Text -> Maybe Text -> HVectElim (DFields q) (DType q) -> q -> RecordTypeSpec (DType q) (DFields q) Source #
The specification for a record. Contains a name, an optional description, the constructor and a description how to parse and serialize fields respecting a given json key.
type RecordTypeSpec t flds = HighSpec t 'SpecRecord flds Source #
A specification for a record
reqField :: FromJSON f => Text -> (t -> f) -> RecordField t f Source #
A required json field. The key must be present in the json.
optField :: FromJSON f => Text -> (t -> Maybe f) -> RecordField t (Maybe f) Source #
An optional json field.
Construct specifications for sum types
sumSpec :: (IsDataSpec q, DContainer q ~ SumOptions) => Text -> Maybe Text -> q -> SumTypeSpec (DType q) (DFields q) Source #
The specification for a sum type. Contains a name, an optional description and a mapping from all constructor (prims) to their respective json fields
type SumTypeSpec t flds = HighSpec t 'SpecSum flds Source #
A specification for an arbitrary sum type
Construct specifications for enum types
enumSpec :: (IsDataSpec q, DContainer q ~ PhantomEnumContainer) => Text -> Maybe Text -> q -> EnumTypeSpec (DType q) (DFields q) Source #
The specification for a classic enum type. Contains a name, an optional description and a mapping from all constructors to ther counterpart json string names.
type EnumTypeSpec t flds = HighSpec t 'SpecEnum flds Source #
A specification for a classic enum
Shared between specifications for simplicity
class IsDataSpec t where Source #
A type class that allows a unified notation for records and sum types. Build specifications
using (:&)
and (.=)
, (.=?)
, (.->)
or (@->)
compileRec :: t -> DContainer t (DType t) (DFields t) Source #
Instances
IsDataSpec (EnumOption t) Source # | |
Defined in Data.HighJson type DFields (EnumOption t) :: [Type] Source # type DType (EnumOption t) Source # type DContainer (EnumOption t) :: Type -> [Type] -> Type Source # compileRec :: EnumOption t -> DContainer (EnumOption t) (DType (EnumOption t)) (DFields (EnumOption t)) Source # | |
IsDataSpec (SumOption t f) Source # | |
IsDataSpec (RecordField t f) Source # | |
Defined in Data.HighJson type DFields (RecordField t f) :: [Type] Source # type DType (RecordField t f) Source # type DContainer (RecordField t f) :: Type -> [Type] -> Type Source # compileRec :: RecordField t f -> DContainer (RecordField t f) (DType (RecordField t f)) (DFields (RecordField t f)) Source # | |
(IsDataSpec x, IsDataSpec y, DType x ~ DType y, DContainer x ~ DContainer y, CombinableContainer (DContainer x)) => IsDataSpec (x :& y) Source # | |
Combination of two local specifications. For records, these are fields, for sum types and enums these are the options.
a :& b infixr 8 |
Instances
Functor ((:&) a) Source # | |
Foldable ((:&) a) Source # | |
Defined in Data.HighJson fold :: Monoid m => (a :& m) -> m # foldMap :: Monoid m => (a0 -> m) -> (a :& a0) -> m # foldMap' :: Monoid m => (a0 -> m) -> (a :& a0) -> m # foldr :: (a0 -> b -> b) -> b -> (a :& a0) -> b # foldr' :: (a0 -> b -> b) -> b -> (a :& a0) -> b # foldl :: (b -> a0 -> b) -> b -> (a :& a0) -> b # foldl' :: (b -> a0 -> b) -> b -> (a :& a0) -> b # foldr1 :: (a0 -> a0 -> a0) -> (a :& a0) -> a0 # foldl1 :: (a0 -> a0 -> a0) -> (a :& a0) -> a0 # elem :: Eq a0 => a0 -> (a :& a0) -> Bool # maximum :: Ord a0 => (a :& a0) -> a0 # minimum :: Ord a0 => (a :& a0) -> a0 # | |
Traversable ((:&) a) Source # | |
(Bounded a, Bounded b) => Bounded (a :& b) Source # | |
(Eq a, Eq b) => Eq (a :& b) Source # | |
(Show a, Show b) => Show (a :& b) Source # | |
(Semigroup a, Semigroup b) => Semigroup (a :& b) Source # | |
(Monoid a, Monoid b) => Monoid (a :& b) Source # | |
(IsDataSpec x, IsDataSpec y, DType x ~ DType y, DContainer x ~ DContainer y, CombinableContainer (DContainer x)) => IsDataSpec (x :& y) Source # | |
type DFields (x :& y) Source # | |
type DType (x :& y) Source # | |
Defined in Data.HighJson | |
type DContainer (x :& y) Source # | |
Defined in Data.HighJson |
Generate json serializers/encoders and parsers from specs
Specification structures
data BodySpec ty a as where Source #
BodySpecRecord :: !(RecordSpec a as) -> BodySpec 'SpecRecord a as | |
BodySpecSum :: !(SumSpec a as) -> BodySpec 'SpecSum a as | |
BodySpecEnum :: !(EnumSpec a) -> BodySpec 'SpecEnum a as |
data RecordField t f Source #
RecordField | |
|
Instances
IsDataSpec (RecordField t f) Source # | |
Defined in Data.HighJson type DFields (RecordField t f) :: [Type] Source # type DType (RecordField t f) Source # type DContainer (RecordField t f) :: Type -> [Type] -> Type Source # compileRec :: RecordField t f -> DContainer (RecordField t f) (DType (RecordField t f)) (DFields (RecordField t f)) Source # | |
type DFields (RecordField t f) Source # | |
Defined in Data.HighJson | |
type DType (RecordField t f) Source # | |
Defined in Data.HighJson | |
type DContainer (RecordField t f) Source # | |
Defined in Data.HighJson |
data RecordSpec a fs Source #
RecordSpec | |
|
data RecordFields t fs where Source #
RFEmpty :: RecordFields t '[] | |
(:+:) :: RecordField t f -> RecordFields t fs -> RecordFields t (f ': fs) infixr 5 |
Instances
CombinableContainer RecordFields Source # | |
Defined in Data.HighJson combineContainer :: forall a (as :: [Type]) (bs :: [Type]). RecordFields a as -> RecordFields a bs -> RecordFields a (Append as bs) Source # |
SumOption | |
|
Instances
IsDataSpec (SumOption t f) Source # | |
type DFields (SumOption t f) Source # | |
Defined in Data.HighJson | |
type DType (SumOption t f) Source # | |
Defined in Data.HighJson | |
type DContainer (SumOption t f) Source # | |
Defined in Data.HighJson |
SumSpec | |
|
data SumOptions t os where Source #
SOEmpty :: SumOptions t '[] | |
(:|:) :: SumOption t o -> SumOptions t os -> SumOptions t (o ': os) infixr 5 |
Instances
CombinableContainer SumOptions Source # | |
Defined in Data.HighJson combineContainer :: forall a (as :: [Type]) (bs :: [Type]). SumOptions a as -> SumOptions a bs -> SumOptions a (Append as bs) Source # |
data EnumOption t Source #
EnumOption | |
|
Instances
IsDataSpec (EnumOption t) Source # | |
Defined in Data.HighJson type DFields (EnumOption t) :: [Type] Source # type DType (EnumOption t) Source # type DContainer (EnumOption t) :: Type -> [Type] -> Type Source # compileRec :: EnumOption t -> DContainer (EnumOption t) (DType (EnumOption t)) (DFields (EnumOption t)) Source # | |
type DFields (EnumOption t) Source # | |
Defined in Data.HighJson | |
type DType (EnumOption t) Source # | |
Defined in Data.HighJson | |
type DContainer (EnumOption t) Source # | |
Defined in Data.HighJson |
EnumSpec | |
|
Aeson reexports
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 writeText
literals. {-# LANGUAGE OverloadedStrings #-} data Coord = Coord { x :: Double, y :: Double } instanceToJSON
Coord wheretoJSON
(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
clause to your
datatype and declare a Generic
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 } derivingGeneric
instanceToJSON
Coord wheretoEncoding
=genericToEncoding
defaultOptions
If on the other hand you wish to customize the generic decoding, you have to implement both methods:
customOptions =defaultOptions
{fieldLabelModifier
=map
toUpper
} instanceToJSON
Coord wheretoJSON
=genericToJSON
customOptionstoEncoding
=genericToEncoding
customOptions
Previous versions of this library only had the toJSON
method. Adding
toEncoding
had two reasons:
- toEncoding is more efficient for the common case that the output of
toJSON
is directly serialized to aByteString
. Further, expressing either method in terms of the other would be non-optimal. - 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 oftoEncoding
usetoJSON
. This produces correct results, but since it performs an intermediate conversion to aValue
, it will be less efficient than directly emitting anEncoding
. (this also means that specifying nothing more thaninstance ToJSON Coord
would be sufficient as a generically decoding instance, but there probably exists no good reason to not specifytoEncoding
in new instances.)
Nothing
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.
instanceToJSON
Coord wheretoEncoding
=genericToEncoding
defaultOptions
toJSONList :: [a] -> Value #
toEncodingList :: [a] -> Encoding #
Instances
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
(ormzero
) 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 writeText
literals. {-# LANGUAGE OverloadedStrings #-} data Coord = Coord { x :: Double, y :: Double } instanceFromJSON
Coord whereparseJSON
(Object
v) = Coord<$>
v.:
"x"<*>
v.:
"y" -- We do not expect a non-Object
value here. -- We could useempty
to fail, buttypeMismatch
-- 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:
instanceFromJSON
Coord whereparseJSON
=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
clause to your
datatype and declare a Generic
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 } derivingGeneric
instanceFromJSON
Coord
The default implementation will be equivalent to
parseJSON =
; if you need different
options, you can customize the generic decoding by defining:genericParseJSON
defaultOptions
customOptions =defaultOptions
{fieldLabelModifier
=map
toUpper
} instanceFromJSON
Coord whereparseJSON
=genericParseJSON
customOptions
Nothing
Instances
Implementation detail structures
newtype PhantomEnumContainer t (ts :: [*]) Source #
Instances
CombinableContainer PhantomEnumContainer Source # | |
Defined in Data.HighJson combineContainer :: forall a (as :: [Type]) (bs :: [Type]). PhantomEnumContainer a as -> PhantomEnumContainer a bs -> PhantomEnumContainer a (Append as bs) Source # |
class CombinableContainer t where Source #
A monoidal type class that respects type level lists associated to the bodies
combineContainer :: t a (as :: [*]) -> t a (bs :: [*]) -> t a (Append as bs) Source #
Instances
CombinableContainer SumOptions Source # | |
Defined in Data.HighJson combineContainer :: forall a (as :: [Type]) (bs :: [Type]). SumOptions a as -> SumOptions a bs -> SumOptions a (Append as bs) Source # | |
CombinableContainer RecordFields Source # | |
Defined in Data.HighJson combineContainer :: forall a (as :: [Type]) (bs :: [Type]). RecordFields a as -> RecordFields a bs -> RecordFields a (Append as bs) Source # | |
CombinableContainer PhantomEnumContainer Source # | |
Defined in Data.HighJson combineContainer :: forall a (as :: [Type]) (bs :: [Type]). PhantomEnumContainer a as -> PhantomEnumContainer a bs -> PhantomEnumContainer a (Append as bs) Source # |