This package provides genericEncodeJson and genericDecodeJson functions for any data types that have a Generic.Rep instance, which can be used to encode or decode Json values or to implement EncodeJson and DecodeJson instances for argonaut-codecs.
Install argonaut-generic with Spago:
spago install argonaut-genericWe can use functions from the Data.Argonaut.Decode.Generic.Rep and Data.Argonaut.Encode.Generic.Rep modules to automatically write instances of DecodeJson and EncodeJson for our data types. The below example defines a recursive sum type, derives Generic, and then uses this library to write its decoding and encoding instances:
import Prelude
import Data.Argonaut.Decode.Class (class DecodeJson)
import Data.Argonaut.Decode.Generic.Rep (genericDecodeJson)
import Data.Argonaut.Encode.Class (class EncodeJson)
import Data.Argonaut.Encode.Generic.Rep (genericEncodeJson)
import Data.Either (Either(..))
import Data.Generic.Rep (class Generic)
data Example
= Either (Either String Example)
| Record { foo :: Int, bar :: String }
| Nested { foo :: { nested :: Int }, bar :: String }
| Product Int Int Example
-- We first need to derive `Generic` for our type
derive instance genericExample :: Generic Example _
-- Necessary to eta-expand because the generic data type is recursive.
instance encodeJsonExample :: EncodeJson Example where
encodeJson a = genericEncodeJson a
instance decodeJson :: DecodeJson Example where
decodeJson a = genericDecodeJson aYou may also be interested in other libraries in the Argonaut ecosystem:
- purescript-argonaut-core defines the
Jsontype, along with basic parsing, printing, and folding functions - purescript-argonaut-codecs provides codecs based on
EncodeJsonandDecodeJsontype classes, along with instances for common data types and combinators for encoding and decodingJsonvalues. - purescript-argonaut-traversals provides prisms, traversals, and a zipper for working with nested
Jsonstructures.
argonaut-generic documentation is stored in a few places:
- Module documentation is published on Pursuit.
- Written documentation is kept in the docs directory.
- Usage examples can be found in the test suite.
If you get stuck, there are several ways to get help:
- Open an issue if you have encountered a bug or problem.
- Ask general questions on the PureScript Discourse forum or the PureScript Discord chat.
You can contribute to argonaut-generic in several ways:
-
If you encounter a problem or have a question, please open an issue. We'll do our best to work with you to resolve or answer it.
-
If you would like to contribute code, tests, or documentation, please read the contributor guide. It's a short, helpful introduction to contributing to this library, including development instructions.
-
If you have written a library, tutorial, guide, or other resource based on this package, please share it on the PureScript Discourse! Writing libraries and learning resources are a great way to help this library succeed.