Copyright |
(c) 2011-2016 Bryan O'Sullivan
(c) 2011 MailRank Inc. |
---|---|
License | BSD3 |
Maintainer | Bryan O'Sullivan <bos@serpentine.com> |
Stability | experimental |
Portability | portable |
Safe Haskell | None |
Language | Haskell2010 |
Types for working with JSON data.
Synopsis
- data Value
- data Key
- type Encoding = Encoding' Value
- unsafeToEncoding :: Builder -> Encoding' a
- fromEncoding :: Encoding' tag -> Builder
- data Series
- type Array = Vector Value
- emptyArray :: Value
- type Pair = ( Key , Value )
- type Object = KeyMap Value
- emptyObject :: Value
- newtype DotNetTime = DotNetTime { }
- typeMismatch :: String -> Value -> Parser a
- unexpected :: Value -> Parser a
- data Parser a
- data Result a
- class FromJSON a where
- fromJSON :: FromJSON a => Value -> Result a
- parse :: (a -> Parser b) -> a -> Result b
- parseEither :: (a -> Parser b) -> a -> Either String b
- parseMaybe :: (a -> Parser b) -> a -> Maybe b
- parseFail :: String -> Parser a
-
class
ToJSON
a
where
- toJSON :: a -> Value
- toEncoding :: a -> Encoding
- toJSONList :: [a] -> Value
- toEncodingList :: [a] -> Encoding
- class KeyValue kv where
- modifyFailure :: ( String -> String ) -> Parser a -> Parser a
- prependFailure :: String -> Parser a -> Parser a
- parserThrowError :: JSONPath -> String -> Parser a
- parserCatchError :: Parser a -> ( JSONPath -> String -> Parser a) -> Parser a
-
class
ToJSONKey
a
where
- toJSONKey :: ToJSONKeyFunction a
- toJSONKeyList :: ToJSONKeyFunction [a]
-
data
ToJSONKeyFunction
a
- = ToJSONKeyText !(a -> Key ) !(a -> Encoding' Key )
- | ToJSONKeyValue !(a -> Value ) !(a -> Encoding )
- toJSONKeyText :: (a -> Text ) -> ToJSONKeyFunction a
- toJSONKeyKey :: (a -> Key ) -> ToJSONKeyFunction a
- contramapToJSONKeyFunction :: (b -> a) -> ToJSONKeyFunction a -> ToJSONKeyFunction b
- class FromJSONKey a where
-
data
FromJSONKeyFunction
a
where
- FromJSONKeyCoerce :: Coercible Text a => FromJSONKeyFunction a
- FromJSONKeyText :: !( Text -> a) -> FromJSONKeyFunction a
- FromJSONKeyTextParser :: !( Text -> Parser a) -> FromJSONKeyFunction a
- FromJSONKeyValue :: !( Value -> Parser a) -> FromJSONKeyFunction a
- fromJSONKeyCoerce :: Coercible Text a => FromJSONKeyFunction a
- coerceFromJSONKeyFunction :: Coercible a b => FromJSONKeyFunction a -> FromJSONKeyFunction b
- mapFromJSONKeyFunction :: (a -> b) -> FromJSONKeyFunction a -> FromJSONKeyFunction b
- class GetConName f => GToJSONKey f
- genericToJSONKey :: ( Generic a, GToJSONKey ( Rep a)) => JSONKeyOptions -> ToJSONKeyFunction a
- class (ConstructorNames f, SumFromString f) => GFromJSONKey f
- genericFromJSONKey :: forall a. ( Generic a, GFromJSONKey ( Rep a)) => JSONKeyOptions -> FromJSONKeyFunction a
- class FromJSON1 f where
- parseJSON1 :: ( FromJSON1 f, FromJSON a) => Value -> Parser (f a)
- class FromJSON2 f where
- parseJSON2 :: ( FromJSON2 f, FromJSON a, FromJSON b) => Value -> Parser (f a b)
-
class
ToJSON1
f
where
- liftToJSON :: (a -> Value ) -> ([a] -> Value ) -> f a -> Value
- liftToJSONList :: (a -> Value ) -> ([a] -> Value ) -> [f a] -> Value
- liftToEncoding :: (a -> Encoding ) -> ([a] -> Encoding ) -> f a -> Encoding
- liftToEncodingList :: (a -> Encoding ) -> ([a] -> Encoding ) -> [f a] -> Encoding
- toJSON1 :: ( ToJSON1 f, ToJSON a) => f a -> Value
- toEncoding1 :: ( ToJSON1 f, ToJSON a) => f a -> Encoding
-
class
ToJSON2
f
where
- liftToJSON2 :: (a -> Value ) -> ([a] -> Value ) -> (b -> Value ) -> ([b] -> Value ) -> f a b -> Value
- liftToJSONList2 :: (a -> Value ) -> ([a] -> Value ) -> (b -> Value ) -> ([b] -> Value ) -> [f a b] -> Value
- liftToEncoding2 :: (a -> Encoding ) -> ([a] -> Encoding ) -> (b -> Encoding ) -> ([b] -> Encoding ) -> f a b -> Encoding
- liftToEncodingList2 :: (a -> Encoding ) -> ([a] -> Encoding ) -> (b -> Encoding ) -> ([b] -> Encoding ) -> [f a b] -> Encoding
- toJSON2 :: ( ToJSON2 f, ToJSON a, ToJSON b) => f a b -> Value
- toEncoding2 :: ( ToJSON2 f, ToJSON a, ToJSON b) => f a b -> Encoding
- class GFromJSON arity f
- data FromArgs arity a
- type GToJSON = GToJSON' Value
- type GToEncoding = GToJSON' Encoding
- class GToJSON' enc arity f
- data ToArgs res arity a
- data Zero
- data One
- genericToJSON :: ( Generic a, GToJSON' Value Zero ( Rep a)) => Options -> a -> Value
- genericLiftToJSON :: ( Generic1 f, GToJSON' Value One ( Rep1 f)) => Options -> (a -> Value ) -> ([a] -> Value ) -> f a -> Value
- genericToEncoding :: ( Generic a, GToJSON' Encoding Zero ( Rep a)) => Options -> a -> Encoding
- genericLiftToEncoding :: ( Generic1 f, GToJSON' Encoding One ( Rep1 f)) => Options -> (a -> Encoding ) -> ([a] -> Encoding ) -> f a -> Encoding
- genericParseJSON :: ( Generic a, GFromJSON Zero ( Rep a)) => Options -> Value -> Parser a
- genericLiftParseJSON :: ( Generic1 f, GFromJSON One ( Rep1 f)) => Options -> ( Value -> Parser a) -> ( Value -> Parser [a]) -> Value -> Parser (f a)
- withObject :: String -> ( Object -> Parser a) -> Value -> Parser a
- withText :: String -> ( Text -> Parser a) -> Value -> Parser a
- withArray :: String -> ( Array -> Parser a) -> Value -> Parser a
- withScientific :: String -> ( Scientific -> Parser a) -> Value -> Parser a
- withBool :: String -> ( Bool -> Parser a) -> Value -> Parser a
- withEmbeddedJSON :: String -> ( Value -> Parser a) -> Value -> Parser a
- pairs :: Series -> Encoding
- foldable :: ( Foldable t, ToJSON a) => t a -> Encoding
- (.:) :: FromJSON a => Object -> Key -> Parser a
- (.:?) :: FromJSON a => Object -> Key -> Parser ( Maybe a)
- (.:!) :: FromJSON a => Object -> Key -> Parser ( Maybe a)
- (.!=) :: Parser ( Maybe a) -> a -> Parser a
- object :: [ Pair ] -> Value
- parseField :: FromJSON a => Object -> Key -> Parser a
- parseFieldMaybe :: FromJSON a => Object -> Key -> Parser ( Maybe a)
- parseFieldMaybe' :: FromJSON a => Object -> Key -> Parser ( Maybe a)
- explicitParseField :: ( Value -> Parser a) -> Object -> Key -> Parser a
- explicitParseFieldMaybe :: ( Value -> Parser a) -> Object -> Key -> Parser ( Maybe a)
- explicitParseFieldMaybe' :: ( Value -> Parser a) -> Object -> Key -> Parser ( Maybe a)
- listEncoding :: (a -> Encoding ) -> [a] -> Encoding
- listValue :: (a -> Value ) -> [a] -> Value
- listParser :: ( Value -> Parser a) -> Value -> Parser [a]
- data Options
- fieldLabelModifier :: Options -> String -> String
- constructorTagModifier :: Options -> String -> String
- allNullaryToStringTag :: Options -> Bool
- omitNothingFields :: Options -> Bool
- sumEncoding :: Options -> SumEncoding
- unwrapUnaryRecords :: Options -> Bool
- tagSingleConstructors :: Options -> Bool
- rejectUnknownFields :: Options -> Bool
-
data
SumEncoding
- = TaggedObject { }
- | UntaggedValue
- | ObjectWithSingleField
- | TwoElemArray
- camelTo :: Char -> String -> String
- camelTo2 :: Char -> String -> String
- defaultOptions :: Options
- defaultTaggedObject :: SumEncoding
- data JSONKeyOptions
- keyModifier :: JSONKeyOptions -> String -> String
- defaultJSONKeyOptions :: JSONKeyOptions
- (<?>) :: Parser a -> JSONPathElement -> Parser a
- type JSONPath = [ JSONPathElement ]
- data JSONPathElement
- formatPath :: JSONPath -> String
- formatRelativePath :: JSONPath -> String
Core JSON types
A JSON value represented as a Haskell value.
Instances
Eq Value Source # | |
Data Value Source # | |
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 Source # gunfold :: ( forall b r. Data b => c (b -> r) -> c r) -> ( forall r. r -> c r) -> Constr -> c Value Source # toConstr :: Value -> Constr Source # dataTypeOf :: Value -> DataType Source # dataCast1 :: Typeable t => ( forall d. Data d => c (t d)) -> Maybe (c Value ) Source # dataCast2 :: Typeable t => ( forall d e. ( Data d, Data e) => c (t d e)) -> Maybe (c Value ) Source # gmapT :: ( forall b. Data b => b -> b) -> Value -> Value Source # gmapQl :: (r -> r' -> r) -> r -> ( forall d. Data d => d -> r') -> Value -> r Source # gmapQr :: forall r r'. (r' -> r -> r) -> r -> ( forall d. Data d => d -> r') -> Value -> r Source # gmapQ :: ( forall d. Data d => d -> u) -> Value -> [u] Source # gmapQi :: Int -> ( forall d. Data d => d -> u) -> Value -> u Source # gmapM :: Monad m => ( forall d. Data d => d -> m d) -> Value -> m Value Source # gmapMp :: MonadPlus m => ( forall d. Data d => d -> m d) -> Value -> m Value Source # gmapMo :: MonadPlus m => ( forall d. Data d => d -> m d) -> Value -> m Value Source # |
|
Ord Value Source # |
The ordering is total, consistent with
Since: 1.5.2.0 |
Defined in Data.Aeson.Types.Internal |
|
Read Value Source # | |
Show Value Source # |
Since version 1.5.6.0 version object values are printed in lexicographic key order
|
IsString Value Source # | |
Defined in Data.Aeson.Types.Internal fromString :: String -> Value Source # |
|
Generic Value Source # | |
NFData Value Source # | |
Defined in Data.Aeson.Types.Internal |
|
Hashable Value Source # | |
FromJSON Value Source # | |
KeyValue Pair Source # | |
KeyValue Object Source # |
Constructs a singleton
|
ToJSON Value Source # | |
Lift Value Source # |
Since: 0.11.0.0 |
GToJSON' Value arity ( U1 :: Type -> Type ) Source # | |
GToJSON' Value arity ( V1 :: Type -> Type ) Source # | |
GToJSON' Encoding arity ( U1 :: Type -> Type ) Source # | |
ToJSON1 f => GToJSON' Value One ( Rec1 f) Source # | |
ToJSON1 f => GToJSON' Encoding One ( Rec1 f) Source # | |
(WriteProduct arity a, WriteProduct arity b, ProductSize a, ProductSize b) => GToJSON' Value arity (a :*: b) Source # | |
ToJSON a => GToJSON' Value arity ( K1 i a :: Type -> Type ) Source # | |
(EncodeProduct arity a, EncodeProduct arity b) => GToJSON' Encoding arity (a :*: b) Source # | |
ToJSON a => GToJSON' Encoding arity ( K1 i a :: Type -> Type ) Source # | |
( ToJSON1 f, GToJSON' Value One g) => GToJSON' Value One (f :.: g) Source # | |
( ToJSON1 f, GToJSON' Encoding One g) => GToJSON' Encoding One (f :.: g) Source # | |
type Rep Value Source # | |
Defined in Data.Aeson.Types.Internal
type
Rep
Value
=
D1
('
MetaData
"Value" "Data.Aeson.Types.Internal" "aeson-2.0.2.0-Hbc7lMoCN3S5f36Jsk6Tpd" '
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
))))
|
Instances
unsafeToEncoding :: Builder -> Encoding' a Source #
Make Encoding from Builder.
Use with care! You have to make sure that the passed Builder is a valid JSON Encoding!
fromEncoding :: Encoding' tag -> Builder Source #
Acquire the underlying bytestring builder.
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)
emptyArray :: Value Source #
The empty array.
emptyObject :: Value Source #
The empty object.
Convenience types and functions
newtype DotNetTime Source #
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.
DotNetTime | |
|
Instances
:: String |
The name of the JSON type being parsed
(
|
-> Value |
The actual value encountered. |
-> Parser a |
Fail parsing due to a type mismatch, with a descriptive message.
The following wrappers should generally be prefered:
withObject
,
withArray
,
withText
,
withBool
.
Error message example
typeMismatch "Object" (String "oops") -- Error: "expected Object, but encountered String"
unexpected :: Value -> Parser a Source #
Fail parsing due to a type mismatch, when the expected types are implicit.
Error message example
unexpected (String "oops") -- Error: "unexpected String"
Type conversion
A JSON parser. N.B. This might not fit your usual understanding of
"parser". Instead you might like to think of
Parser
as a "parse result",
i.e. a parser to which the input has already been applied.
The result of running a
Parser
.
Instances
class FromJSON a where Source #
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
fromJSON :: FromJSON a => Value -> Result a Source #
Convert a value from JSON, failing if the types do not match.
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 Source #
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 Source #
toEncodingList :: [a] -> Encoding Source #