Safe Haskell | Safe-Inferred |
---|---|
Language | Haskell2010 |
the operations on JSON data types
Synopsis
- class AtKey2 vk v where
- class AtKey vk v where
- encodeT :: ToJSON a => a -> Text
- fromJSONmaybe :: FromJSON a => Value -> Maybe a
- fromJSONm :: (FromJSON a, Show a) => Value -> ErrIO a
- fromJSONerrio :: (FromJSON a, Show a) => Value -> ErrIO a
- fromJSONfailError :: (FromJSON a, Show a) => Value -> ErrIO a
- result1 :: (Monad m, MonadFail m) => Result a -> m a
- gak :: AsValue s => s -> Key -> Maybe Value
- mergeLeftPref :: [Value] -> Value
- unions' :: [KeyMap Value] -> KeyMap Value
- mergeRightPref :: [Value] -> Value
- unObject :: Value -> Object
- type ErrIO = ExceptT Text IO
- data Value
- class ToJSON a where
- toJSON :: a -> Value
- toEncoding :: a -> Encoding
- toJSONList :: [a] -> Value
- toEncodingList :: [a] -> Encoding
- class FromJSON a where
- fromJSON :: FromJSON a => Value -> Result a
- decode :: FromJSON a => ByteString -> Maybe a
- omitNothingFields :: Options -> Bool
- eitherDecode :: FromJSON a => ByteString -> Either String a
- object :: [Pair] -> Value
- (.=) :: (KeyValue kv, ToJSON v) => Key -> v -> kv
- genericParseJSON :: (Generic a, GFromJSON Zero (Rep a)) => Options -> Value -> Parser a
- defaultOptions :: Options
- genericToJSON :: (Generic a, GToJSON' Value Zero (Rep a)) => Options -> a -> Value
- fieldLabelModifier :: Options -> String -> String
- fromList :: (Eq k, Hashable k) => [(k, v)] -> HashMap k v
- toList :: HashMap k v -> [(k, v)]
- data Result a
- encode :: ToJSON a => a -> ByteString
- encodePretty :: ToJSON a => a -> ByteString
- parseEither :: (a -> Parser b) -> a -> Either String b
- parseMaybe :: (a -> Parser b) -> a -> Maybe b
Documentation
class AtKey vk v where Source #
get and set at a key
getAtKey :: vk -> Key -> Maybe v Source #
getAt2Key :: vk -> Key -> Key -> Maybe v Source #
two keys: one after the other
fromJSONfailError :: (FromJSON a, Show a) => Value -> ErrIO a Source #
converts fromJson to a record structure throws error if fails
mergeLeftPref :: [Value] -> Value Source #
The (left-biased) union of two maps. all values must be objects, which can be prooduced with toJSON It prefers the first map when duplicate keys are encountered, http://hackage.haskell.org/package/hashmap-1.3.3/docs/Data-HashMap.html mergeLeftPref = Object . HML.unions . map unObject for ghc 9.2.1
mergeRightPref :: [Value] -> Value Source #
A JSON value represented as a Haskell value.
Instances
Arbitrary Value | Since: aeson-2.0.3.0 |
CoArbitrary Value | Since: aeson-2.0.3.0 |
Defined in Data.Aeson.Types.Internal coarbitrary :: Value -> Gen b -> Gen b # | |
Function Value | Since: aeson-2.0.3.0 |
FromJSON Value | |
FromString Encoding | |
Defined in Data.Aeson.Types.ToJSON fromString :: String -> Encoding | |
FromString Value | |
Defined in Data.Aeson.Types.ToJSON fromString :: String -> Value | |
ToJSON Value | |
Defined in Data.Aeson.Types.ToJSON | |
Data Value | |
Defined in Data.Aeson.Types.Internal gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Value -> c Value # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c Value # dataTypeOf :: Value -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c Value) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c Value) # gmapT :: (forall b. Data b => b -> b) -> Value -> Value # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Value -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Value -> r # gmapQ :: (forall d. Data d => d -> u) -> Value -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Value -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Value -> m Value # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Value -> m Value # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Value -> m Value # | |
IsString Value | |
Defined in Data.Aeson.Types.Internal fromString :: String -> Value # | |
Generic Value | |
Read Value | |
Show Value | Since version 1.5.6.0 version object values are printed in lexicographic key order
|
NFData Value | |
Defined in Data.Aeson.Types.Internal | |
Eq Value | |
Ord Value | The ordering is total, consistent with Since: aeson-1.5.2.0 |
Hashable Value | |
Defined in Data.Aeson.Types.Internal | |
AsJSON Value | |
AsNumber Value | |
AsValue Value | |
Zeros Value Source # | |
NiceStrings Value Source # | |
Lift Value | Since: aeson-0.11.0.0 |
AtKey Value Value Source # | |
AtKey Value Text Source # | |
AtKey Value Integer Source # | |
AtKey Value Bool Source # | |
ToJSON a => AtKey2 Value a Source # | |
(GToJSON' Encoding arity a, ConsToJSON Encoding arity a, Constructor c) => SumToJSON' TwoElemArray Encoding arity (C1 c a) | |
Defined in Data.Aeson.Types.ToJSON | |
(GToJSON' Value arity a, ConsToJSON Value arity a, Constructor c) => SumToJSON' TwoElemArray Value arity (C1 c a) | |
Defined in Data.Aeson.Types.ToJSON | |
GToJSON' Encoding arity (U1 :: TYPE LiftedRep -> Type) | |
GToJSON' Encoding arity (V1 :: TYPE LiftedRep -> Type) | |
GToJSON' Value arity (U1 :: TYPE LiftedRep -> Type) | |
GToJSON' Value arity (V1 :: TYPE LiftedRep -> Type) | |
ToJSON1 f => GToJSON' Encoding One (Rec1 f) | |
ToJSON1 f => GToJSON' Value One (Rec1 f) | |
(EncodeProduct arity a, EncodeProduct arity b) => GToJSON' Encoding arity (a :*: b) | |
ToJSON a => GToJSON' Encoding arity (K1 i a :: TYPE LiftedRep -> Type) | |
(WriteProduct arity a, WriteProduct arity b, ProductSize a, ProductSize b) => GToJSON' Value arity (a :*: b) | |
ToJSON a => GToJSON' Value arity (K1 i a :: TYPE LiftedRep -> Type) | |
(ToJSON1 f, GToJSON' Encoding One g) => GToJSON' Encoding One (f :.: g) | |
(ToJSON1 f, GToJSON' Value One g) => GToJSON' Value One (f :.: g) | |
FromPairs Value (DList Pair) | |
Defined in Data.Aeson.Types.ToJSON | |
v ~ Value => KeyValuePair v (DList Pair) | |
Defined in Data.Aeson.Types.ToJSON | |
type Rep Value | |
Defined in Data.Aeson.Types.Internal type Rep Value = D1 ('MetaData "Value" "Data.Aeson.Types.Internal" "aeson-2.1.2.1-1CP91TiqJNMKhmZsERtItU" 'False) ((C1 ('MetaCons "Object" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Object)) :+: (C1 ('MetaCons "Array" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Array)) :+: C1 ('MetaCons "String" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Text)))) :+: (C1 ('MetaCons "Number" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Scientific)) :+: (C1 ('MetaCons "Bool" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Bool)) :+: C1 ('MetaCons "Null" 'PrefixI 'False) (U1 :: Type -> Type)))) | |
type Index Value | |
Defined in Data.Aeson.Lens | |
type IxValue Value | |
Defined in Data.Aeson.Lens |
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
or more conveniently using the DerivingVia extension
deriving viaGenerically
Coord instanceToJSON
Coord
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 oftoJSON
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
or using the DerivingVia extension
deriving viaGenerically
Coord 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
fromJSON :: FromJSON a => Value -> Result a #
Convert a value from JSON, failing if the types do not match.
decode :: FromJSON a => ByteString -> Maybe a #
Efficiently deserialize a JSON value from a lazy ByteString
.
If this fails due to incomplete or invalid input, Nothing
is
returned.
The input 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.
omitNothingFields :: Options -> Bool #
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
.
Note that this does not affect parsing: Maybe
fields are
optional regardless of the value of omitNothingFields
, subject
to the note below.
Note
Setting omitNothingFields
to True
only affects fields which are of
type Maybe
uniformly in the ToJSON
instance.
In particular, if the type of a field is declared as a type variable, it
will not be omitted from the JSON object, unless the field is
specialized upfront in the instance.
The same holds for Maybe
fields being optional in the FromJSON
instance.
Example
The generic instance for the following type Fruit
depends on whether
the instance head is Fruit a
or Fruit (Maybe a)
.
data Fruit a = Fruit { apples :: a -- A field whose type is a type variable. , oranges ::Maybe
Int } derivingGeneric
-- apples required, oranges optional -- Even iffromJSON
is then specialized to (Fruit (Maybe
a)). instanceFromJSON
a =>FromJSON
(Fruit a) -- apples optional, oranges optional -- In this instance, the field apples is uniformly of type (Maybe
a). instanceFromJSON
a =>FromJSON
(Fruit (Maybe
a)) options ::Options
options =defaultOptions
{omitNothingFields
=True
} -- apples always present in the output, oranges is omitted ifNothing
instanceToJSON
a =>ToJSON
(Fruit a) wheretoJSON
=genericToJSON
options -- both apples and oranges are omitted ifNothing
instanceToJSON
a =>ToJSON
(Fruit (Maybe
a)) wheretoJSON
=genericToJSON
options
eitherDecode :: FromJSON a => ByteString -> Either String a #
Like decode
but returns an error message when decoding fails.
genericParseJSON :: (Generic a, GFromJSON Zero (Rep a)) => Options -> Value -> Parser a #
A configurable generic JSON decoder. This function applied to
defaultOptions
is used as the default for parseJSON
when the
type is an instance of Generic
.
Default encoding Options
:
Options
{fieldLabelModifier
= id ,constructorTagModifier
= id ,allNullaryToStringTag
= True ,omitNothingFields
= False ,sumEncoding
=defaultTaggedObject
,unwrapUnaryRecords
= False ,tagSingleConstructors
= False ,rejectUnknownFields
= False }
genericToJSON :: (Generic a, GToJSON' Value Zero (Rep a)) => Options -> a -> Value #
A configurable generic JSON creator. This function applied to
defaultOptions
is used as the default for toJSON
when the type
is an instance of Generic
.
fieldLabelModifier :: Options -> String -> String #
Function applied to field labels. Handy for removing common record prefixes for example.
fromList :: (Eq k, Hashable k) => [(k, v)] -> HashMap k v #
\(O(n)\) Construct a map with the supplied mappings. If the list contains duplicate mappings, the later mappings take precedence.
toList :: HashMap k v -> [(k, v)] #
\(O(n)\) Return a list of this map's elements. The list is produced lazily. The order of its elements is unspecified.
The result of running a Parser
.
Instances
MonadFail Result | |
Defined in Data.Aeson.Types.Internal | |
Foldable Result | |
Defined in Data.Aeson.Types.Internal fold :: Monoid m => Result m -> m # foldMap :: Monoid m => (a -> m) -> Result a -> m # foldMap' :: Monoid m => (a -> m) -> Result a -> m # foldr :: (a -> b -> b) -> b -> Result a -> b # foldr' :: (a -> b -> b) -> b -> Result a -> b # foldl :: (b -> a -> b) -> b -> Result a -> b # foldl' :: (b -> a -> b) -> b -> Result a -> b # foldr1 :: (a -> a -> a) -> Result a -> a # foldl1 :: (a -> a -> a) -> Result a -> a # elem :: Eq a => a -> Result a -> Bool # maximum :: Ord a => Result a -> a # minimum :: Ord a => Result a -> a # | |
Traversable Result | |
Alternative Result | |
Applicative Result | |
Functor Result | |
Monad Result | |
MonadPlus Result | |
Monoid (Result a) | |
Semigroup (Result a) | |
Show a => Show (Result a) | |
NFData a => NFData (Result a) | |
Defined in Data.Aeson.Types.Internal | |
Eq a => Eq (Result a) | |
encode :: ToJSON a => a -> ByteString #
Efficiently serialize a JSON value as a lazy ByteString
.
This is implemented in terms of the ToJSON
class's toEncoding
method.
encodePretty :: ToJSON a => a -> ByteString #
parseEither :: (a -> Parser b) -> a -> Either String b #