Package

purescript-argonaut-codecs

Repository
purescript-contrib/purescript-argonaut-codecs
License
MIT
Uploaded by
garyb
Published on
2019-05-06T19:33:57Z

Latest release Build status Pursuit Maintainer: garyb Maintainer: thomashoneyman

EncodeJson and DecodeJson classes and instances, useful combinators for encoding and decoding Json values.

Installation

bower install purescript-argonaut-codecs

Documentation

Module documentation is published on Pursuit.

Example

Using purescript-argonaut-core we can build a simple Json object:

someObject =
  let
    objects =
      [ jsonSingletonObject "bar" (fromString "a")
      , jsonSingletonObject "bar" (fromString "b")
      ]
  in
    fromObject $ Object.fromFoldable [ Tuple "foo" (fromArray objects) ]

The decodeJson, .:, .:?, and .!= functions provided in this module make it straightforward to decode this JSON to a custom data type and serialize that custom data type back to JSON:

newtype MyType = MyType
  { foo :: String
  , bar :: Maybe Int
  , baz :: Boolean
  }

-- create a `DecodeJson` instance
instance decodeJsonMyType :: DecodeJson MyType where
  decodeJson json = do
    x <- decodeJson json
    foo <- x .: "foo" -- mandatory field
    bar <- x .:? "bar" -- optional field
    baz <- x .:? "baz" .!= false -- optional field with default value of `false`
    pure $ MyType { foo, bar, baz }

-- or pass a function
decodeMyTypes :: Json -> Either String (Array MyType)
decodeMyTypes json = do
  x <- decodeJson json
  arr <- x .: "myTypes"
  for arr decodeJson

-- create a `EncodeJson` instance
instance encodeJsonMyType :: EncodeJson MyType where
  encodeJson (MyType x) =
    "foo" := x.foo 
      ~> "bar" :=? x.bar 
      ~>? "baz" := x.baz -- optional field
      ~> jsonEmptyObject

Contributing

Read the contribution guidelines to get started and see helpful related resources.