Package

purescript-argonaut-codecs

Repository
purescript-contrib/purescript-argonaut-codecs
License
MIT
Uploaded by
thomashoneyman
Published on
2018-11-24

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 interrogate the Json object:

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 ~>? -- optional field
    "baz" := x.baz ~>
    jsonEmptyObject

Contributing

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