| 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 :: 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
- 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
data HighSpec a (ty :: SpecType) as #
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 writeTextliterals. {-# LANGUAGE OverloadedStrings #-} data Coord = Coord { x :: Double, y :: Double } instanceToJSONCoord 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 GenericToJSON 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
If on the other hand you wish to customize the generic decoding, you have to implement both methods:
customOptions =defaultOptions{fieldLabelModifier=maptoUpper} instanceToJSONCoord wheretoJSON=genericToJSONcustomOptionstoEncoding=genericToEncodingcustomOptions
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
toJSONis 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
toEncodingstill compile and have the correct semantics. This is ensured by making the default implementation oftoEncodingusetoJSON. 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 Coordwould be sufficient as a generically decoding instance, but there probably exists no good reason to not specifytoEncodingin 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.
instanceToJSONCoord wheretoEncoding=genericToEncodingdefaultOptions
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:
emptyandmzerowork, but are terse and uninformative;failyields a custom error message;typeMismatchproduces 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 writeTextliterals. {-# LANGUAGE OverloadedStrings #-} data Coord = Coord { x :: Double, y :: Double } instanceFromJSONCoord whereparseJSON(Objectv) = Coord<$>v.:"x"<*>v.:"y" -- We do not expect a non-Objectvalue here. -- We could usemzeroto fail, buttypeMismatch-- gives a much more informative error message.parseJSONinvalid =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:
instanceFromJSONCoord 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 GenericFromJSON 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
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=maptoUpper} instanceFromJSONCoord whereparseJSON=genericParseJSONcustomOptions
Instances
| FromJSON Bool | |
| FromJSON Char | |
| FromJSON Double | |
| FromJSON Float | |
| FromJSON Int | |
| FromJSON Int8 | |
| FromJSON Int16 | |
| FromJSON Int32 | |
| FromJSON Int64 | |
| FromJSON Integer | WARNING: Only parse Integers from trusted input since an
attacker could easily fill up the memory of the target system by
specifying a scientific number with a big exponent like
|
| FromJSON Natural | |
| FromJSON Ordering | |
| FromJSON Word | |
| FromJSON Word8 | |
| FromJSON Word16 | |
| FromJSON Word32 | |
| FromJSON Word64 | |
| FromJSON () | |
| FromJSON Scientific | |
| FromJSON Number | |
| FromJSON Text | |
| FromJSON UTCTime | |
| FromJSON Value | |
| FromJSON DotNetTime | |
| FromJSON Text | |
| FromJSON Version | |
| FromJSON CTime | |
| FromJSON IntSet | |
| FromJSON ZonedTime | Supported string formats:
The first space may instead be a |
| FromJSON LocalTime | |
| FromJSON TimeOfDay | |
| FromJSON NominalDiffTime | WARNING: Only parse lengths of time from trusted input
since an attacker could easily fill up the memory of the target
system by specifying a scientific number with a big exponent like
|
| FromJSON DiffTime | WARNING: Only parse lengths of time from trusted input
since an attacker could easily fill up the memory of the target
system by specifying a scientific number with a big exponent like
|
| FromJSON Day | |
| FromJSON UUID | |
| FromJSON a => FromJSON [a] | |
| FromJSON a => FromJSON (Maybe a) | |
| (FromJSON a, Integral a) => FromJSON (Ratio a) | |
| HasResolution a => FromJSON (Fixed a) | WARNING: Only parse fixed-precision numbers from trusted input
since an attacker could easily fill up the memory of the target
system by specifying a scientific number with a big exponent like
|
| FromJSON a => FromJSON (Min a) | |
| FromJSON a => FromJSON (Max a) | |
| FromJSON a => FromJSON (First a) | |
| FromJSON a => FromJSON (Last a) | |
| FromJSON a => FromJSON (WrappedMonoid a) | |
| FromJSON a => FromJSON (Option a) | |
| FromJSON a => FromJSON (NonEmpty a) | |
| FromJSON a => FromJSON (Identity a) | |
| FromJSON a => FromJSON (Dual a) | |
| FromJSON a => FromJSON (First a) | |
| FromJSON a => FromJSON (Last a) | |
| FromJSON a => FromJSON (IntMap a) | |
| FromJSON v => FromJSON (Tree v) | |
| FromJSON a => FromJSON (Seq a) | |
| (Ord a, FromJSON a) => FromJSON (Set a) | |
| FromJSON a => FromJSON (DList a) | |
| (Prim a, FromJSON a) => FromJSON (Vector a) | |
| (Storable a, FromJSON a) => FromJSON (Vector a) | |
| (Vector Vector a, FromJSON a) => FromJSON (Vector a) | |
| (Eq a, Hashable a, FromJSON a) => FromJSON (HashSet a) | |
| FromJSON a => FromJSON (Vector a) | |
| (FromJSON a, FromJSON b) => FromJSON (Either a b) | |
| (FromJSON a, FromJSON b) => FromJSON (a, b) | |
| (FromJSON v, FromJSONKey k, Eq k, Hashable k) => FromJSON (HashMap k v) | |
| (FromJSONKey k, Ord k, FromJSON v) => FromJSON (Map k v) | |
| FromJSON (Proxy k a) | |
| (FromJSON a, FromJSON b, FromJSON c) => FromJSON (a, b, c) | |
| FromJSON a => FromJSON (Const k a b) | |
| FromJSON b => FromJSON (Tagged k a b) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d) => FromJSON (a, b, c, d) | |
| (FromJSON1 f, FromJSON1 g, FromJSON a) => FromJSON (Product * f g a) | |
| (FromJSON1 f, FromJSON1 g, FromJSON a) => FromJSON (Sum * f g a) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e) => FromJSON (a, b, c, d, e) | |
| (FromJSON1 f, FromJSON1 g, FromJSON a) => FromJSON (Compose * * f g a) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f) => FromJSON (a, b, c, d, e, f) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g) => FromJSON (a, b, c, d, e, f, g) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h) => FromJSON (a, b, c, d, e, f, g, h) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i) => FromJSON (a, b, c, d, e, f, g, h, i) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i, FromJSON j) => FromJSON (a, b, c, d, e, f, g, h, i, j) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i, FromJSON j, FromJSON k) => FromJSON (a, b, c, d, e, f, g, h, i, j, k) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i, FromJSON j, FromJSON k, FromJSON l) => FromJSON (a, b, c, d, e, f, g, h, i, j, k, l) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i, FromJSON j, FromJSON k, FromJSON l, FromJSON m) => FromJSON (a, b, c, d, e, f, g, h, i, j, k, l, m) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i, FromJSON j, FromJSON k, FromJSON l, FromJSON m, FromJSON n) => FromJSON (a, b, c, d, e, f, g, h, i, j, k, l, m, n) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i, FromJSON j, FromJSON k, FromJSON l, FromJSON m, FromJSON n, FromJSON o) => FromJSON (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) | |
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) #