Safe Haskell | None |
---|---|
Language | Haskell2010 |
Data.HighJson
Contents
- 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
- data HighSpec a ty 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
- 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
- class FromJSON a where
- newtype PhantomEnumContainer t ts = PhantomEnumContainer {
- unPhantomEnumContainer :: [EnumOption t]
- class CombinableContainer t where
A json specification for any type
Constructors
HighSpec | |
Fields
|
Constructors
SpecRecord | |
SpecSum | |
SpecEnum |
Construct specifications for records
recSpec :: (IsDataSpec q, DContainer q ~ RecordFields) => Text -> Maybe Text -> HVectElim (DFields q) (DType q) -> q -> RecordTypeSpec (DType q) (DFields q) #
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 #
A specification for a record
reqField :: FromJSON f => Text -> (t -> f) -> RecordField t f #
A required json field. The key must be present in the json.
optField :: FromJSON f => Text -> (t -> Maybe f) -> RecordField t (Maybe f) #
An optional json field.
Construct specifications for sum types
sumSpec :: (IsDataSpec q, DContainer q ~ SumOptions) => Text -> Maybe Text -> q -> SumTypeSpec (DType q) (DFields q) #
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 #
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) #
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 #
A specification for a classic enum
enumOpt :: Text -> Prism' t () -> EnumOption t #
An option of a classic enum
Shared between specifications for simplicity
class IsDataSpec t where #
A type class that allows a unified notation for records and sum types. Build specifications using '(:&)' and '(.=)', '(.=?)', '(.->)' or '(@->)'
Minimal complete definition
Methods
compileRec :: t -> DContainer t (DType t) (DFields t) #
Instances
IsDataSpec (EnumOption t) # | |
IsDataSpec (SumOption t f) # | |
IsDataSpec (RecordField t f) # | |
(IsDataSpec x, IsDataSpec y, (~) * (DType x) (DType y), (~) (* -> [*] -> *) (DContainer x) (DContainer y), CombinableContainer (DContainer x)) => IsDataSpec ((:&) x y) # | |
Combination of two local specifications. For records, these are fields, for sum types and enums these are the options.
Constructors
a :& b infixr 8 |
Instances
Functor ((:&) a) # | |
Foldable ((:&) a) # | |
Traversable ((:&) a) # | |
(Bounded b, Bounded a) => Bounded ((:&) a b) # | |
(Eq b, Eq a) => Eq ((:&) a b) # | |
(Show b, Show a) => Show ((:&) a b) # | |
(Monoid a, Monoid b) => Monoid ((:&) a b) # | |
(IsDataSpec x, IsDataSpec y, (~) * (DType x) (DType y), (~) (* -> [*] -> *) (DContainer x) (DContainer y), CombinableContainer (DContainer x)) => IsDataSpec ((:&) x y) # | |
type DFields ((:&) x y) # | |
type DType ((:&) x y) # | |
type DContainer ((:&) x y) # | |
Generate json serializers/encoders and parsers from specs
Specification structures
Constructors
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 #
Constructors
RecordField | |
Fields
|
Instances
IsDataSpec (RecordField t f) # | |
type DFields (RecordField t f) # | |
type DType (RecordField t f) # | |
type DContainer (RecordField t f) # | |
data RecordSpec a fs #
Constructors
RecordSpec | |
Fields
|
data RecordFields t fs where #
Constructors
RFEmpty :: RecordFields t '[] | |
(:+:) :: RecordField t f -> RecordFields t fs -> RecordFields t (f ': fs) infixr 5 |
Instances
Constructors
SumOption | |
Fields
|
Constructors
SumSpec | |
Fields
|
data SumOptions t os where #
Constructors
SOEmpty :: SumOptions t '[] | |
(:|:) :: SumOption t o -> SumOptions t os -> SumOptions t (o ': os) infixr 5 |
Instances
data EnumOption t #
Constructors
EnumOption | |
Fields
|
Instances
IsDataSpec (EnumOption t) # | |
type DFields (EnumOption t) # | |
type DType (EnumOption t) # | |
type DContainer (EnumOption t) # | |
Constructors
EnumSpec | |
Fields
|
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 to 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.)
Methods
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:
empty
andmzero
work, but are terse and uninformative;fail
yields a custom error message;typeMismatch
produces an informative message for cases when the value encountered is not of the expected type.
An example type and instance using typeMismatch
:
-- 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 usemzero
to fail, buttypeMismatch
-- gives a much more informative error message.parseJSON
invalid =typeMismatch
"Coord" invalid
For this common case of only being concerned with a single
type of JSON value, the functions withObject
, withNumber
, 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
Instances
Implementation detail structures
newtype PhantomEnumContainer t ts #
Constructors
PhantomEnumContainer | |
Fields
|
Instances
class CombinableContainer t where #
A monoidal type class that respects type level lists associated to the bodies
Minimal complete definition
Methods
combineContainer :: t a (as :: [*]) -> t a (bs :: [*]) -> t a (Append as bs) #