map package:autodocodec

Map a codec for decoding bs into a decoder for as. This is useful for building discriminatedUnionCodecs.
Wrap up a value of type b with its codec to produce and encoder for as that ignores its input and instead encodes the value b. This is useful for building discriminatedUnionCodecs.
Encode a Map, and decode any Map.

API Note

This is a forward-compatible version of MapCodec.
mapCodec = MapCodec
Encode a Map, and decode any Map.
Map a codec in both directions. This is not strictly dimap, because the decoding function is allowed to fail, but we can implement dimap using this function by using a decoding function that does not fail. Otherwise we would have to have another constructor here.
Encode a HashMap, and decode any HashMap.
Map a codec's input and output types. This function allows you to have the parsing fail in a new way. If you use this function, then you will most likely want to add documentation about how not every value that the schema specifies will be accepted. This function is like BimapCodec except it also combines one level of a nested BimapCodecs.

Example usage

logLevelCodec :: JSONCodec LogLevel logLevelCodec = bimapCodec parseLogLevel renderLogLevel codec ? "Valid values include DEBUG, INFO, WARNING, ERROR."
Map both directions of a codec You can use this function to change the type of a codec as long as the two functions are inverses.

HasCodec instance for newtypes

A good use-case is implementing HasCodec for newtypes:
newtype MyInt = MyInt { unMyInt :: Int }
instance HasCodec MyInt where
codec = dimapCodec MyInt unMyInt codec
Map the input part of a codec You can use this function if you only need to map the rendering-side of a codec. This function is probably only useful if the function you map does not change the codec type. WARNING: This can be used to produce a codec that does not roundtrip.
>>> toJSONVia (lmapCodec (*2) (codec :: JSONCodec Int)) 5
Number 10.0
Map the output part of a codec You can use this function if you only need to map the parsing-side of a codec. This function is probably only useful if the function you map does not change the codec type. WARNING: This can be used to produce a codec that does not roundtrip.
>>> JSON.parseMaybe (parseJSONVia (rmapCodec (*2) codec)) (Number 5) :: Maybe Int
Just 10
Encode a HashMap, and decode any HashMap.

API Note

This is a forward-compatible version of HashMapCodec.
hashMapCodec = HashMapCodec
Encode a KeyMap, and decode any KeyMap. This chooses hashMapCodec or mapCodec based on ordered-keymap flag in aeson.