| Copyright | (C) 2026 - Eitan Chatav |
|---|---|
| License | BSD-style (see the file LICENSE) |
| Maintainer | Eitan Chatav <eitan.chatav@gmail.com> |
| Stability | provisional |
| Portability | non-portable |
| Safe Haskell | None |
| Language | Haskell2010 |
Control.Lens.Grammar.Json
Description
A Json grammar of a type parses, prints & encodes its JSON,
compatibly with aeson, & types it in TypeScript, all at once.
Deriving
A Generic type derives its grammar, by aeson's default options.
>>>:{data Person = Person {name :: Text, age :: Int, email :: Maybe Text} deriving stock (Show, Generic) deriving anyclass Json :}
>>>LByteString.putStrLn (encodingToLazyByteString (jsonEncode (Person "Ada" 36 Nothing))){"name":"Ada","age":36,"email":null}>>>jsonDecode @Person "{\"name\":\"Ada\",\"age\":36}"Right (Person {name = "Ada", age = 36, email = Nothing})
Failures are located, & name what they expected.
>>>either explain show (jsonDecode @Person "{\"name\":\"Ada\",\"age\":\"36\"}")"Error in $.age: expected Int, but found \"36\""
aeson
ViaJson derives aeson's instances, & jsonGeneric takes
aeson's Options.
>>>:{data Pet = Cat | Dog deriving stock (Show, Generic) deriving (Aeson.ToJSON, Aeson.FromJSON) via ViaJson Pet instance Json Pet where json = jsonGeneric Aeson.defaultOptions {Aeson.constructorTagModifier = map toLower} :}
>>>Aeson.encode [Cat, Dog]"[\"cat\",\"dog\"]"
Grammars
A grammar is written once, with the combinators of JsonVal,
JsonObj, JsonTup & JsonStr, & ruleTyped names its type.
>>>:{data Point = Point Double Double deriving stock Show instance Json Point where json = ruleTyped $ iso (\(Point x y) -> (x, y)) (uncurry Point) >~ jsonObject ("x" !: json >*< "y" ?: json != 0) :}
>>>jsonDecode @Point "{\"x\":1}"Right (Point 1.0 0.0)>>>jsonPrint (Point 1 0)Object (fromList [("x",Number 1.0)])
A tuple is an array of elements, & a sum is the alternative grammars of its constructors, here tagged by string literals.
>>>:{data Shape = Circle Double | Rectangle Double Double deriving stock Show _Circle :: Prism' Shape Double _Circle = prism' Circle (\case Circle r -> Just r; _ -> Nothing) _Rectangle :: Prism' Shape (Double, Double) _Rectangle = prism' (uncurry Rectangle) (\case Rectangle w h -> Just (w, h); _ -> Nothing) instance Json Shape where json = ruleTyped $ orP [ _Circle >? jsonObject ("kind" !: "circle" >* "radius" !: json) , _Rectangle >? jsonObject ("kind" !: "rectangle" >* "size" !: jsonTuple (jsonElem json >*< jsonElem json)) ] :}
>>>LByteString.putStrLn (encodingToLazyByteString (jsonEncode [Circle 1, Rectangle 2 3]))[{"kind":"circle","radius":1.0},{"kind":"rectangle","size":[2.0,3.0]}]
Types
jsonTsPut puts the TypeScript declarations of types' JSON,
which jsonTsDeclarations declares, by Control.Lens.Grammar.TypeScript,
& jsonType types.
>>>jsonTsPut (type '[Person, Point, Shape]) stdoutexport type Double = number | null | "+inf" | "-inf"; export type Int = number; export type Person = { name: string; age: Int; email?: null | string }; export type Point = { x: Double; y?: Double }; export type Shape = { kind: "circle"; radius: Double } | { kind: "rectangle"; size: [Double, Double] };
Synopsis
- class Json a where
- jsonGeneric :: forall a (d :: Meta) (f :: Type -> Type) p. (Generic a, Rep a ~ D1 d f, GSum f, Typeable a, EnumTag (AllNullary f) a, JsonVal p) => Options -> p a a
- jsonParse :: Json a => Value -> Either JsonError a
- jsonDecode :: Json a => ByteString -> Either JsonError a
- jsonPrint :: Json a => a -> Value
- jsonErrorPrint :: Json a => a -> Either JsonError Value
- jsonEncode :: Json a => a -> Encoding
- jsonErrorEncode :: Json a => a -> Either JsonError Encoding
- newtype ViaJson a = ViaJson a
- class (CocartesianChoice p, Filtrator p, JsonStr p) => JsonVal (p :: Type -> Type -> Type) where
- jsonNull :: p () ()
- jsonBool :: p Bool Bool
- jsonNumber :: p Scientific Scientific
- jsonInt :: p Int Int
- jsonInt8 :: p Int8 Int8
- jsonInt16 :: p Int16 Int16
- jsonInt32 :: p Int32 Int32
- jsonInt64 :: p Int64 Int64
- jsonWord :: p Word Word
- jsonWord8 :: p Word8 Word8
- jsonWord16 :: p Word16 Word16
- jsonWord32 :: p Word32 Word32
- jsonWord64 :: p Word64 Word64
- jsonInteger :: p Integer Integer
- jsonNatural :: p Natural Natural
- jsonDouble :: p Double Double
- jsonArray :: p a b -> p [a] [b]
- jsonNullable :: p a b -> p (Maybe a) (Maybe b)
- jsonPair :: p a b -> p c d -> p (a, c) (b, d)
- jsonTag :: Text -> p a b -> p a b
- jsonMap :: Ord b => (forall (k :: Type -> Type -> Type). JsonStr k => k a b) -> p c d -> p (Map a c) (Map b d)
- jsonHashMap :: (Eq b, Hashable b) => (forall (k :: Type -> Type -> Type). JsonStr k => k a b) -> p c d -> p (HashMap a c) (HashMap b d)
- jsonTuple :: (forall (q :: Type -> Type -> Type). JsonTup p q => q a b) -> p a b
- jsonObject :: (forall (q :: Type -> Type -> Type). JsonObj p q => q a b) -> p a b
- jsonObjectStrict :: (forall (q :: Type -> Type -> Type). JsonObj p q => q a b) -> p a b
- jsonValue :: p Value Value
- class (Monoidal q, CocartesianChoice q) => JsonObj (p :: Type -> Type -> Type) (q :: Type -> Type -> Type) | q -> p where
- (!=) :: (Eq a, Profunctor q) => q (Maybe a) (Maybe a) -> a -> q a a
- class Alternator q => JsonTup (p :: Type -> Type -> Type) (q :: Type -> Type -> Type) | q -> p where
- jsonElem :: p a b -> q a b
- class (Cochoice p, forall x y. (x ~ (), y ~ ()) => IsString (p x y), forall x y. BackusNaurForm (p x y)) => JsonStr (p :: Type -> Type -> Type) where
- jsonText :: p Text Text
- jsonString :: p String String
- jsonEncodedText :: APrism Text (Text, Encoding' Text) a a -> p a a
- jsonEnumWith :: (a -> Int) -> [(Text, a)] -> p a a
- jsonEnum :: JsonStr p => AComonocle a a () () -> (a -> Text) -> p a a
- jsonType :: forall a -> Json a => Bnf JsonType
- jsonTsDeclarations :: forall (as :: [Type]) -> All Json as => [TsDeclaration]
- jsonTsPut :: forall (as :: [Type]) -> All Json as => Handle -> IO ()
- data JsonType
- data JsonElements
- data JsonProperty
- data JsonError = JsonError {}
- data JsonErrorSort
- jsonErrorMessage :: JsonError -> String
Json
A type with a JSON grammar, like aeson's ToJSON
& FromJSON together, which every JsonVal interprets.
Its methods default to aeson's defaults, & json to the
Generic grammar, by aeson's default options.
Minimal complete definition
Nothing
Methods
json :: JsonVal p => p a a Source #
default json :: forall (d :: Meta) (f :: Type -> Type) p. (Generic a, Rep a ~ D1 d f, GSum f, Typeable a, EnumTag (AllNullary f) a, JsonVal p) => p a a Source #
jsonList :: JsonVal p => p [a] [a] Source #
toJSONList & parseJSONList,
as one grammar, an array of values by default.
Char and wrappers override it, so that a String is a JSON string.
jsonKey :: Maybe (forall (k :: Type -> Type -> Type). JsonStr k => k a a) Source #
toJSONKey & parseJSONKey
as one grammar for the text keys of objects,
or else Nothing for the keys of arrays of pairs.
jsonKeyList :: Maybe (forall (k :: Type -> Type -> Type). JsonStr k => k [a] [a]) Source #
toJSONKeyList & parseJSONKeyList
as one grammar for keys of lists, like jsonList.
Char and wrappers override it.
jsonOmitField :: Maybe (APrism' a ()) Source #
omitField & omittedField together,
as the value of a record's field which may be omitted, like nearly:
it matches the value omitted by omitNothingFields,
& reviews the value of a field omitted by allowOmittedFields.
Instances
jsonGeneric :: forall a (d :: Meta) (f :: Type -> Type) p. (Generic a, Rep a ~ D1 d f, GSum f, Typeable a, EnumTag (AllNullary f) a, JsonVal p) => Options -> p a a Source #
jsonDecode :: Json a => ByteString -> Either JsonError a Source #
eitherDecode, which reads the JSON text by aeson,
failing by its message for text which isn't JSON.
jsonErrorPrint :: Json a => a -> Either JsonError Value Source #
jsonPrint, failing where the grammar doesn't print a value,
like a key which repeats.
>>>jsonErrorPrint (1 :: Int)Right (Number 1.0)
jsonEncode :: Json a => a -> Encoding Source #
jsonErrorEncode :: Json a => a -> Either JsonError Encoding Source #
jsonEncode, failing where the grammar doesn't print a value.
aeson's instances, derived from a Json instance, failing to parse
at the path of a JsonError, by its message: ToJSON &
FromJSON, with their fields omitted by jsonOmitField, &
ToJSONKey & FromJSONKey, by jsonKey & jsonKeyList,
or else as values, in arrays of pairs.
data Point = Point {x :: Int, y :: Int}
deriving stock Generic
deriving anyclass Json
deriving (ToJSON, FromJSON) via ViaJson PointConstructors
| ViaJson a |
Instances
| Json a => FromJSON (ViaJson a) Source # | |
Defined in Control.Lens.Grammar.Json | |
| Json a => FromJSONKey (ViaJson a) Source # | |
Defined in Control.Lens.Grammar.Json Methods fromJSONKey :: FromJSONKeyFunction (ViaJson a) # | |
| Json a => ToJSON (ViaJson a) Source # | |
| Json a => ToJSONKey (ViaJson a) Source # | |
Defined in Control.Lens.Grammar.Json | |
| Show a => Show (ViaJson a) Source # | |
| Eq a => Eq (ViaJson a) Source # | |
| Ord a => Ord (ViaJson a) Source # | |
Grammar
class (CocartesianChoice p, Filtrator p, JsonStr p) => JsonVal (p :: Type -> Type -> Type) where Source #
JsonVal grammars describe JSON values: null, booleans, numbers,
strings, by JsonStr, arrays & objects, by JsonTup & JsonObj.
As CocartesianChoices & Filtrators, they have alternatives
(>+<, >|<) & partial isomorphisms (>?, ?<).
Its numbers are bounded, & its integers integral, as aeson's are.
Minimal complete definition
Methods
jsonBool :: p Bool Bool Source #
jsonNumber :: p Scientific Scientific Source #
jsonInt8 :: p Int8 Int8 Source #
jsonInt16 :: p Int16 Int16 Source #
jsonInt32 :: p Int32 Int32 Source #
jsonInt64 :: p Int64 Int64 Source #
jsonWord :: p Word Word Source #
jsonWord8 :: p Word8 Word8 Source #
jsonWord16 :: p Word16 Word16 Source #
jsonWord32 :: p Word32 Word32 Source #
jsonWord64 :: p Word64 Word64 Source #
jsonInteger :: p Integer Integer Source #
jsonNatural :: p Natural Natural Source #
jsonDouble :: p Double Double Source #
jsonArray :: p a b -> p [a] [b] Source #
A homogeneous JSON array, like TypeScript's T[], which is a tuple
of a rest element, though interpreters may define it more efficiently.
jsonArray p = jsonTuple (manyP (jsonElem p))
jsonNullable :: p a b -> p (Maybe a) (Maybe b) Source #
null or a value, like aeson's Maybe,
though interpreters may define it more efficiently.
jsonNullable p = eotMaybe >~ jsonNull >+< p
jsonPair :: p a b -> p c d -> p (a, c) (b, d) Source #
A pair, as an array of its two elements, though interpreters may define it more efficiently.
jsonPair p q = jsonTuple (jsonElem p >*< jsonElem q)
jsonTag :: Text -> p a b -> p a b Source #
An object of a single property, as aeson tags Either's & sums'
values, though interpreters may define it more efficiently.
jsonTag k p = jsonObjectStrict (k !: p)
jsonMap :: Ord b => (forall (k :: Type -> Type -> Type). JsonStr k => k a b) -> p c d -> p (Map a c) (Map b d) Source #
jsonHashMap :: (Eq b, Hashable b) => (forall (k :: Type -> Type -> Type). JsonStr k => k a b) -> p c d -> p (HashMap a c) (HashMap b d) Source #
jsonTuple :: (forall (q :: Type -> Type -> Type). JsonTup p q => q a b) -> p a b Source #
jsonObject :: (forall (q :: Type -> Type -> Type). JsonObj p q => q a b) -> p a b Source #
jsonObjectStrict :: (forall (q :: Type -> Type -> Type). JsonObj p q => q a b) -> p a b Source #
A jsonObject which rejects the properties that it doesn't name.
class (Monoidal q, CocartesianChoice q) => JsonObj (p :: Type -> Type -> Type) (q :: Type -> Type -> Type) | q -> p where Source #
JsonObj grammars describe the properties of a JSON object.
Each key may be read or written at most once.
A required property, k !: v, is like TypeScript's {k: T},
and an optional property, k ?: v, may be missing, like {k?: T}.
A property with a default, "limit" ?: jsonInt != 10,
like aeson's .:? & .!=, is missing exactly when it's the default.
Its properties are JsonVal grammars, which determine its type.
Methods
(!:) :: Text -> p a b -> q a b infixr 7 Source #
(?:) :: Text -> p a b -> q (Maybe a) (Maybe b) infixr 7 Source #
jsonDict :: (forall (k :: Type -> Type -> Type). JsonStr k => k a b) -> p c d -> q [(a, c)] [(b, d)] Source #
The properties of an object which aren't named by !: or ?:,
as a list of key-value pairs, by a grammar of keys & a grammar of values.
On its own, it's a dictionary.
jsonObject (jsonDict jsonText json)
-- {"a": 1, "b": 2} <-> [("a", 1), ("b", 2)]Beside named properties, it's the rest of them.
jsonObject ("id" !: json >*< jsonDict jsonText json)
-- {"id": 1, "a": true, "b": false} <-> (1, [("a", True), ("b", False)])Parsing fails unless every remaining property matches both grammars,
so a narrower key grammar than jsonText, like jsonEnumWith,
restricts the keys allowed. Printing fails on a key which repeats,
or which is also named. An object has at most one jsonDict.
In TypeScript, it's an index signature, { [key: string]: T },
or, of an enumeration of keys, a mapped type, { [key in K]?: T }.
Arguments
| :: (Eq a, Profunctor q) | |
| => q (Maybe a) (Maybe a) | optional |
| -> a | default |
| -> q a a |
class Alternator q => JsonTup (p :: Type -> Type -> Type) (q :: Type -> Type -> Type) | q -> p where Source #
class (Cochoice p, forall x y. (x ~ (), y ~ ()) => IsString (p x y), forall x y. BackusNaurForm (p x y)) => JsonStr (p :: Type -> Type -> Type) where Source #
fromString s = only s ?< jsonString
jsonString = iso Text.pack Text.unpack >~ jsonText
Minimal complete definition
Methods
jsonText :: p Text Text Source #
jsonString :: p String String Source #
jsonEncodedText :: APrism Text (Text, Encoding' Text) a a -> p a a Source #
A string matched from its Text, which is reviewed lazily
as both its Text & an aeson string Encoding',
either of which an interpreter uses.
jsonEnumWith :: (a -> Int) -> [(Text, a)] -> p a a Source #
An enumeration of strings, which a map's key may be,
like TypeScript's union of string literals, "a" | "b",
by a table of strings & their values, & the index of each value in it,
so that printing needn't search it.
jsonEnum :: JsonStr p => AComonocle a a () () -> (a -> Text) -> p a a Source #
An enumeration of strings, by AComonocle's copies & their names,
which jsonEnumWith tables once, numbered as fromEnumerable numbers them.
>>>import Control.Lens (coerced)>>>import Control.Lens.Comonocle (_BoundedEnum)>>>import Data.Text qualified as Text>>>newtype Order = Order Ordering deriving (Show)>>>let name = Text.toLower . Text.pack . show @Ordering>>>instance Json Order where json = coerced >~ jsonEnum _BoundedEnum name>>>jsonPrint (Order GT)String "gt">>>jsonParse @Order (Aeson.String "lt")Right (Order LT)
Types
jsonType :: forall a -> Json a => Bnf JsonType Source #
The type of the JSON of a type, by its rules, which are named by their qualified names.
>>>jsonType (type Bool)Bnf {startBnf = JsonBoolean, rulesBnf = fromList []}>>>jsonType (Maybe Ordering)Bnf {startBnf = JsonUnion [JsonNull,JsonRule "GHC.Types.Ordering"], rulesBnf = fromList [("GHC.Types.Ordering",JsonUnion [JsonLiteral "LT",JsonLiteral "EQ",JsonLiteral "GT"])]}
jsonTsDeclarations :: forall (as :: [Type]) -> All Json as => [TsDeclaration] Source #
Type the JSON of types, in TypeScript, as a declaration of each rule
of their types, named by its unqualified name, or else its qualified name,
which jsonTsPut puts.
>>>jsonTsDeclarations (type '[Maybe Ordering])[TypeAliasDeclaration [ExportKeyword] "Ordering" [] (UnionType [LiteralType (TextLiteral "LT"),LiteralType (TextLiteral "EQ"),LiteralType (TextLiteral "GT")])]
jsonTsPut :: forall (as :: [Type]) -> All Json as => Handle -> IO () Source #
Put the TypeScript declarations of the JSON of types to a handle,
like a .ts file.
>>>jsonTsPut (type '[Maybe Ordering]) stdoutexport type Ordering = "LT" | "EQ" | "GT";
The type of JSON values, which a grammar describes,
of rules by their names, in a Bnf, as jsonType describes them.
It's the union of its alternatives, so that falseP is the type of
no values.
Constructors
| JsonRule String | the type of a rule, by its name |
| JsonNull | null |
| JsonBoolean |
|
| JsonNumber | numbers |
| JsonString | strings |
| JsonLiteral Text | a string |
| JsonSubtype JsonType | some values of a type |
| JsonArray JsonElements | arrays of elements |
| JsonObject [JsonProperty] | objects of properties |
| JsonUnion [JsonType] | values of any of some types |
data JsonElements Source #
The JsonElements of a JsonArray are the KleeneStarAlgebra generated by JsonType.
Constructors
| JsonElement JsonType | an element |
| JsonElements JsonElements | elements, repeated any number of times |
| JsonElements1 JsonElements | elements, repeated at least once |
| JsonElementsOpt JsonElements | elements, or none |
| JsonElementsTup [JsonElements] | elements, in sequence |
| JsonElementsAlt [JsonElements] | elements, any of some alternatives |
Instances
data JsonProperty Source #
A property of a JsonObject.
Constructors
| JsonProperty Text Bool JsonType | a property, by its key, which is optional or not |
| JsonDict JsonType JsonType | the rest of the properties, by the types of their keys & values |
Instances
| Read JsonProperty Source # | |
Defined in Control.Lens.Grammar.Json Methods readsPrec :: Int -> ReadS JsonProperty # readList :: ReadS [JsonProperty] # | |
| Show JsonProperty Source # | |
Defined in Control.Lens.Grammar.Json Methods showsPrec :: Int -> JsonProperty -> ShowS # show :: JsonProperty -> String # showList :: [JsonProperty] -> ShowS # | |
| Eq JsonProperty Source # | |
Defined in Control.Lens.Grammar.Json | |
| Ord JsonProperty Source # | |
Defined in Control.Lens.Grammar.Json Methods compare :: JsonProperty -> JsonProperty -> Ordering # (<) :: JsonProperty -> JsonProperty -> Bool # (<=) :: JsonProperty -> JsonProperty -> Bool # (>) :: JsonProperty -> JsonProperty -> Bool # (>=) :: JsonProperty -> JsonProperty -> Bool # max :: JsonProperty -> JsonProperty -> JsonProperty # min :: JsonProperty -> JsonProperty -> JsonProperty # | |
Errors
A located failure to decode, parse or print a Value.
Its path is relative to that Value, root first.
It expected one of the alternatives, none meaning just "unexpected".
Parsing found a Value, or decoding found text which isn't JSON,
by aeson's message; printing doesn't show the Haskell value it found.
It failed within rules, outermost first, branching where alternatives
failed alike; a rule it failed for as a whole is its expectation instead.
Constructors
| JsonError | |
Fields | |
data JsonErrorSort Source #
How a JsonError failed, so that alternatives report the closest.
Constructors
| JsonIlliteral | a string literal mismatch; the alternative doesn't apply |
| JsonMismatch | the value was rejected as a whole |
| JsonMissing | the value was rejected for what it contains, lacks or repeats |
Instances
| Show JsonErrorSort Source # | |
Defined in Control.Lens.Grammar.Json Methods showsPrec :: Int -> JsonErrorSort -> ShowS # show :: JsonErrorSort -> String # showList :: [JsonErrorSort] -> ShowS # | |
| Eq JsonErrorSort Source # | |
Defined in Control.Lens.Grammar.Json Methods (==) :: JsonErrorSort -> JsonErrorSort -> Bool # (/=) :: JsonErrorSort -> JsonErrorSort -> Bool # | |
| Ord JsonErrorSort Source # | |
Defined in Control.Lens.Grammar.Json Methods compare :: JsonErrorSort -> JsonErrorSort -> Ordering # (<) :: JsonErrorSort -> JsonErrorSort -> Bool # (<=) :: JsonErrorSort -> JsonErrorSort -> Bool # (>) :: JsonErrorSort -> JsonErrorSort -> Bool # (>=) :: JsonErrorSort -> JsonErrorSort -> Bool # max :: JsonErrorSort -> JsonErrorSort -> JsonErrorSort # min :: JsonErrorSort -> JsonErrorSort -> JsonErrorSort # | |