/purescript-argonaut-codecs

JSON serialization and deserialization with Argonaut.

Primary LanguagePureScriptMIT LicenseMIT

Argonaut Codecs

CI Release Pursuit Maintainer: thomashoneyman

Argonaut is a collection of libraries for working with JSON in PureScript. argonaut-codecs provides codecs based on the EncodeJson and DecodeJson type classes, along with instances for common data types and combinators for encoding and decoding Json values.

You may also be interested in these other libraries from the Argonaut ecosystem:

The quick start will get you up and running with the basics of argonaut-codecs. For a deeper dive, please see the full documentation for this library, which includes an in-depth tutorial.

Installation

Install argonaut-codecs with Spago:

spago install argonaut-codecs

or install it as part of the Argonaut bundle:

spago install argonaut

Quick start

Use encodeJson to encode PureScript data types as Json and decodeJson to decode Json into PureScript types, with helpful error messages if decoding fails.

type User = { name :: String, age :: Maybe Int }

-- We get encoding and decoding for free because of the `EncodeJson` instances
-- for records, strings, integers, and `Maybe`, along with many other common
-- PureScript types.

userToJson :: User -> Json
userToJson = encodeJson

userFromJson :: Json -> Either JsonDecodeError User
userFromJson = decodeJson

In a REPL we can see these functions in action:

> type User = { name :: String, age :: Maybe Int }
> user = { name: "Tom", age: Just 25 }
> stringify (encodeJson user)
"{\"name\":\"Tom\",\"age\":25}"

> (decodeJson =<< parseJson """{ "name": "Tom", "age": 25 }""") :: Either JsonDecodeError User
Right { name: "Tom", age: Just 25 }

> res = (decodeJson =<< parseJson """{ "name": "Tom" }""") :: Either JsonDecodeError User
> res
Left (AtKey "age" MissingValue)

# You can print errors
> lmap printJsonDecodeError res
Left "An error occurred while decoding a JSON value:\n  At object key 'age':\n  No value was found."

Documentation

argonaut-codecs documentation is stored in a few places:

  1. Module documentation is published on Pursuit.
  2. Written documentation is kept in the docs directory.
  3. Usage examples can be found in the test suite.

If you get stuck, there are several ways to get help:

Contributing

You can contribute to argonaut-codecs in several ways:

  1. 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.

  2. 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.

  3. 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.