EncodeJson
and DecodeJson
classes and instances, useful combinators for encoding and decoding Json
values.
bower install purescript-argonaut-codecs
Module documentation is published on Pursuit.
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
Read the contribution guidelines to get started and see helpful related resources.