https://github.com/juspay/purescript-foreign-generic
https://github.com/juspay/purescript-foreign-generic
Last synced: 6 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/juspay/purescript-foreign-generic
- Owner: juspay
- License: other
- Created: 2023-03-15T13:48:02.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2023-03-15T13:52:31.000Z (over 3 years ago)
- Last Synced: 2025-07-01T21:25:39.271Z (about 1 year ago)
- Language: PureScript
- Size: 74.2 KB
- Stars: 0
- Watchers: 4
- Forks: 3
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# purescript-foreign-generic
[](https://travis-ci.org/paf31/purescript-foreign-generic)
Generic deriving for `purescript-foreign`.
- [Module Documentation](generated-docs/Foreign/Generic.md)
- [Example](test/Main.purs)
- [Further examples in this repo](https://github.com/justinwoo/purescript-howto-foreign-generic)
## Example Usage
First, define some data type and derive `Generic`:
```purescript
> import Prelude
> import Data.Generic.Rep (class Generic)
> import Data.Show.Generic (genericShow)
> newtype MyRecord = MyRecord { a :: Int }
> derive instance genericMyRecord :: Generic MyRecord _
> instance showMyRecord :: Show MyRecord where show = genericShow
```
To encode JSON, use `genericEncodeJSON`:
```purescript
> import Foreign.Generic (defaultOptions, genericEncodeJSON)
> opts = defaultOptions { unwrapSingleConstructors = true }
> genericEncodeJSON opts (MyRecord { a: 1 })
"{\"a\":1}"
```
And to decode JSON, use `genericDecodeJSON`:
```purescript
> import Control.Monad.Except (runExcept)
> import Foreign.Generic (genericDecodeJSON)
> runExcept (genericDecodeJSON opts "{\"a\":1}" :: _ MyRecord)
(Right (MyRecord { a: 1 }))
```
Badly formed JSON will result in a useful error, which can be inspected or pretty-printed:
```purescript
> import Data.Bifunctor (lmap)
> import Foreign (renderForeignError)
> lmap (map renderForeignError) $ runExcept (genericDecodeJSON opts "{\"a\":\"abc\"}" :: _ MyRecord)
(Left
(NonEmptyList
(NonEmpty
"Error at array index 0: (ErrorAtProperty \"a\" (TypeMismatch \"Int\" \"String\"))"
Nil)))
```